JavaScript版DateAdd和DateDiff函数代码_javascript技巧
程序员文章站
2022-05-11 15:22:03
...
DateAdd函数:
function DateAdd(interval,number,date){
switch(interval.toLowerCase()){
case "y": return new Date(date.setFullYear(date.getFullYear()+number));
case "m": return new Date(date.setMonth(date.getMonth()+number));
case "d": return new Date(date.setDate(date.getDate()+number));
case "w": return new Date(date.setDate(date.getDate()+7*number));
case "h": return new Date(date.setHours(date.getHours()+number));
case "n": return new Date(date.setMinutes(date.getMinutes()+number));
case "s": return new Date(date.setSeconds(date.getSeconds()+number));
case "l": return new Date(date.setMilliseconds(date.getMilliseconds()+number));
}
}
DateDiff函数:
function DateDiff(interval,date1,date2){
var long = date2.getTime() - date1.getTime(); //相差毫秒
switch(interval.toLowerCase()){
case "y": return parseInt(date2.getFullYear() - date1.getFullYear());
case "m": return parseInt((date2.getFullYear() - date1.getFullYear())*12 + (date2.getMonth()-date1.getMonth()));
case "d": return parseInt(long/1000/60/60/24);
case "w": return parseInt(long/1000/60/60/24/7);
case "h": return parseInt(long/1000/60/60);
case "n": return parseInt(long/1000/60);
case "s": return parseInt(long/1000);
case "l": return parseInt(long);
}
}
兼容多浏览器的datediff函数
复制代码 代码如下:
function DateAdd(interval,number,date){
switch(interval.toLowerCase()){
case "y": return new Date(date.setFullYear(date.getFullYear()+number));
case "m": return new Date(date.setMonth(date.getMonth()+number));
case "d": return new Date(date.setDate(date.getDate()+number));
case "w": return new Date(date.setDate(date.getDate()+7*number));
case "h": return new Date(date.setHours(date.getHours()+number));
case "n": return new Date(date.setMinutes(date.getMinutes()+number));
case "s": return new Date(date.setSeconds(date.getSeconds()+number));
case "l": return new Date(date.setMilliseconds(date.getMilliseconds()+number));
}
}
DateDiff函数:
复制代码 代码如下:
function DateDiff(interval,date1,date2){
var long = date2.getTime() - date1.getTime(); //相差毫秒
switch(interval.toLowerCase()){
case "y": return parseInt(date2.getFullYear() - date1.getFullYear());
case "m": return parseInt((date2.getFullYear() - date1.getFullYear())*12 + (date2.getMonth()-date1.getMonth()));
case "d": return parseInt(long/1000/60/60/24);
case "w": return parseInt(long/1000/60/60/24/7);
case "h": return parseInt(long/1000/60/60);
case "n": return parseInt(long/1000/60);
case "s": return parseInt(long/1000);
case "l": return parseInt(long);
}
}
兼容多浏览器的datediff函数
复制代码 代码如下:
推荐阅读
-
JavaScript 模仿vbs中的 DateAdd() 函数的代码
-
php实现的DateDiff和DateAdd时间函数代码分享
-
vbscript和javascript版的15位, 18位的身份证号码的验证函数.以及根据身份证取省份,生日,性别
-
JavaScript 模仿vbs中的 DateAdd() 函数的代码
-
Js代码优化规则和技巧(JavaScript优化)
-
基于jquery的高性能td和input切换并可修改内容实现代码_javascript技巧
-
JavaScript中URL编码函数代码_javascript技巧
-
js获得当前时区夏令时发生和终止的时间代码_javascript技巧
-
按下回车键指向下一个位置的一个函数代码_javascript技巧
-
js/ajax跨越访问-jsonp的原理和实例(javascript和jquery实现代码)_javascript技巧