JavaScript实现日期加减计算功能代码实例,因为在js中没有类似C#中的AddDays方法,所以要想实现日期加减的话,就需要自己写函数来实现。这里就是通过重写Js Date对象的prototype,扩展了增加日期的方法,方便日后使用:
01
<script language="javascript">
02
Date.prototype.Format = function(fmt)
03
{
04
//代码作者: meizz
05
var o =
06
{
07
"M+" : this.getMonth() + 1, //月份
08
"d+" : this.getDate(), //日
09
"h+" : this.getHours(), //小时
10
"m+" : this.getMinutes(), //分
11
"s+" : this.getSeconds(), //秒
12
"q+" : Math.floor((this.getMonth() + 3) / 3), //季度
13
"S" : this.getMilliseconds() //毫秒
14
};
15
if (/(y+)/.test(fmt))
16
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
17
for (var k in o)
18
if (new RegExp("(" + k + ")").test(fmt))
19
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
20
return fmt;
21
}
22
Date.prototype.addDays = function(d)
23
{
24
this.setDate(this.getDate() + d);
25
};
26
Date.prototype.addWeeks = function(w)
27
{
28
this.addDays(w * 7);
29
};
30
Date.prototype.addMonths= function(m)
31
{
32
var d = this.getDate();
33
this.setMonth(this.getMonth() + m);
34
if (this.getDate() < d)
35
this.setDate(0);
36
};
37
Date.prototype.addYears = function(y)
38
{
39
var m = this.getMonth();
40
this.setFullYear(this.getFullYear() + y);
41
if (m < this.getMonth())
42
{
43
this.setDate(0);
44
}
45
};
46
</script>
请把上述代码拷贝到页面中,使用方法举例,调用addDays实现将天数加1,也就是显示明天的日期,把以下代码同样复制到页面中,放在区域内:
1
<script language="javascript">
2
//使用举例,将日期加1天:
3
var now = new Date();
4
now.addDays(1);//加减日期
5
alert(now.Format("yyyy-MM-dd"));//测试输出
6
</script>
高度以alert方式来显示结果,你会看到弹出的日期是明天的日期,也就是今天+1天。