Javascript 日期对象Date扩展方法


Posted in Javascript onMay 30, 2009

今天在网上摘抄了些js中操作日期的相关方法,现在与大家分享一下。

<script type="text/javascript"> 
Date.prototype.Format = function(fmt) 
{ 
//author: meizz 
var o = 
{ 
"M+" : this.getMonth() + 1, //月份 
"d+" : this.getDate(), //日 
"h+" : this.getHours(), //小时 
"m+" : this.getMinutes(), //分 
"s+" : this.getSeconds(), //秒 
"q+" : Math.floor((this.getMonth() + 3) / 3), //季度 
"S" : this.getMilliseconds() //毫秒 
}; 
if (/(y+)/.test(fmt)) 
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); 
for (var k in o) 
if (new RegExp("(" + k + ")").test(fmt)) 
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); 
return fmt; 
} 
Date.prototype.addDays = function(d) 
{ 
this.setDate(this.getDate() + d); 
}; 
Date.prototype.addWeeks = function(w) 
{ 
this.addDays(w * 7); 
}; 
Date.prototype.addMonths= function(m) 
{ 
var d = this.getDate(); 
this.setMonth(this.getMonth() + m); 
if (this.getDate() < d) 
this.setDate(0); 
}; 
Date.prototype.addYears = function(y) 
{ 
var m = this.getMonth(); 
this.setFullYear(this.getFullYear() + y); 
if (m < this.getMonth()) 
{ 
this.setDate(0); 
} 
}; 
//测试 var now = new Date(); now.addDays(1);//加减日期操作 alert(now.Format("yyyy-MM-dd")); 
Date.prototype.dateDiff = function(interval,endTime) 
{ 
switch (interval) 
{ 
case "s": //?算秒差 
return parseInt((endTime-this)/1000); 
case "n": //?算分差 
return parseInt((endTime-this)/60000); 
case "h": //?算?r差 
return parseInt((endTime-this)/3600000); 
case "d": //?算日差 
return parseInt((endTime-this)/86400000); 
case "w": //?算?差 
return parseInt((endTime-this)/(86400000*7)); 
case "m": //?算月差 
return (endTime.getMonth()+1)+((endTime.getFullYear()-this.getFullYear())*12)-(this.getMonth()+1); 
case "y": //?算年差 
return endTime.getFullYear()-this.getFullYear(); 
default: //?入有? 
return undefined; 
} 
} 
//测试 var starTime = new Date("2007/05/12 07:30:00"); var endTime = new Date("2008/06/12 08:32:02"); document.writeln("秒差: "+starTime .dateDiff("s",endTime )+"<br>"); document.writeln("分差: "+starTime .dateDiff("n",endTime )+"<br>"); document.writeln("?r差: "+starTime .dateDiff("h",endTime )+"<br>"); document.writeln("日差: "+starTime .dateDiff("d",endTime )+"<br>"); document.writeln("?差: "+starTime .dateDiff("w",endTime )+"<br>"); document.writeln("月差: "+starTime .dateDiff("m",endTime )+"<br>"); document.writeln("年差: "+starTime .dateDiff("y",endTime )+"<br>"); 
</script>

具体扩展的方法如下:
parseCHS--静态方法。解析常用的中文日期并返回日期对象。
add--日期加减操作。[注:此函数在上传时还存在一个BUG。请下载后把此函数内的第一行"var regExp = /^\d+$/;" 改为 "var regExp = /^([+-])?\d+$/;", 要不然就做不了减法。]
dateDiff--日期差。开始日期与当前日期的差,返回差的绝对值。
getFirstWeekDays--获取当前日期所在年份中第一个星期的天数。
getLastWeekDays--获取当前日期所在年份中最后一个星期的天数。
getWeeksOfYear--获取当前日期所在年份的周数。
getWeek--获取当前日期所在是一年中的第几周。返回一个整数值。
getSeason--获取当前日期所在是一年中的第几季。返回一个季度整数值。
详细注释及参数,请参考JS文件内的注释。

/* 
===================================================================================== 
Description:Date对象扩展。包括常用中文日期格式解析、加减操作、日期差、周操作和季操作。 
Author:Dezwen. 
Date:2009-5-30. 
===================================================================================== 
*/ 
Date.parseCHS = function(dateString) { 
///<summary> 
///解析常用的中文日期并返回日期对象。 
///</summary> 
///<param name="dateString" type="string"> 
///日期字符串。包含的格式有:"xxxx(xx)-xx-xx xx:xx:xx","xxxx(xx).xx.xx xx:xx:xx", 
///"xxxx(xx)年xx月xx日 xx时xx分xx秒" 
///</param> 
var regExp1 = /^\d{4}-\d{1,2}-\d{1,2}( \d{1,2}:\d{1,2}:\d{1,2})?$/; 
var regExp2 = /^\d{4}\.\d{1,2}\.\d{1,2}( \d{1,2}:\d{1,2}:\d{1,2})?$/; 
var regExp3 = /^\d{4}年\d{1,2}月\d{1,2}日( \d{1,2}时\d{1,2}分\d{1,2}秒)?$/; 
if (regExp1.test(dateString)) { } 
else if (regExp2.test(dateString)) { 
dateString = dateString.replace(/\./g, "-"); 
} 
else if (regExp3.test(dateString)) { 
dateString = dateString.replace("年", "-").replace( 
"月", "-").replace("日", "").replace("时", ":").replace("分", ":" 
).replace("秒", ""); 
} 
else { 
throw "传给Date.parseCHS的参数值的格式不正确。请传递一个有效的日期格式字符串作为参数。"; 
} 
var date_time = dateString.split(" "); 
var date_part = date_time[0].split("-"); 
var time_part = (date_time.length > 1 ? date_time[1].split(":") : ""); 
if (time_part == "") { 
return new Date(date_part[0], date_part[1] - 1, date_part[2]); 
} 
else { 
return new Date(date_part[0], date_part[1] - 1, date_part[2], time_part[0], time_part[1], time_part[2]); 
} 
} 
Date.prototype.add = function(datepart, number, returnNewObjec) { 
///<summary> 
///日期加减。 
///若returnNewObjec参数为true值,则操作结果由一个新的日期对象返回,原日期对象不变, 
///否则返回的是原日期对象,此时原日期对象的值是操作结果. 
///</summary> 
///<param name="datepart" type="string"> 
///日期加减的部分: 
///Year, yy, yyyy--年 
///quarter, qq, q --季 
///Month, mm, m -- 月 
///dayofyear, dy, y-- 日 
///Day, dd, d -- 日 
///Week, wk, ww -- 周 
///Hour, hh -- 小时 
///minute, mi, n -- 分钟 
///second, ss, s -- 秒 
///millisecond, ms -- 毫秒 
///</param> 
///<param name="number" type="int"> 
///要加减的数量 
///</param> 
///<param name="returnNewObjec" type="bool"> 
///是否返回新的日期对象。若参数为true值,则返回一个新的日期对象,否则返回的是当前日期对象. 
///</param> 
///<returns type="Date"> 
///返回一个日期对象 
///</returns> 
var regExp = /^\d+$/; 
if (regExp.test(number)) { 
number = parseInt(number); 
} 
else { number = 0; } 
datepart = datepart.toLowerCase(); 
var tDate; 
if (typeof (returnNewObjec) == "boolean") { 
if (returnNewObjec == true) { 
tDate = new Date(this); 
} 
else { tDate = this; } 
} 
else { tDate = this; } switch (datepart) { 
case "year": 
case "yy": 
case "yyyy": 
tDate.setFullYear(this.getFullYear() + number); 
break; 
case "quarter": 
case "qq": 
case "q": 
tDate.setMonth(this.getMonth() + (number * 3)); 
break; 
case "month": 
case "mm": 
case "m": 
tDate.setMonth(this.getMonth() + number); 
break; 
case "dayofyear": 
case "dy": 
case "y": 
case "day": 
case "dd": 
case "d": 
tDate.setDate(this.getDate() + number); 
break; 
case "week": 
case "wk": 
case "ww": 
tDate.setDate(this.getDate() + (number * 7)); 
break; 
case "hour": 
case "hh": 
tDate.setHours(this.getHours() + number); 
break 
case "minute": 
case "mi": 
case "n": 
tDate.setMinutes(this.getMinutes() + number); 
break 
case "second": 
case "ss": 
case "s": 
tDate.setSeconds(this.getSeconds() + number); 
break; 
case "millisecond": 
case "ms": 
tDate.setMilliseconds(this.getMilliseconds() + number); 
break; 
} 
return tDate; 
} 
Date.prototype.dateDiff = function(datepart, beginDate) { 
///<summary> 
///开始日期与当前日期的差,返回差的绝对值。 
///</summary> 
///<param name="datepart" type="string"> 
///日期加减的部分: 
///Year, yy, yyyy--年 ; 
///quarter, qq, q --季 
///Month, mm, m -- 月 
///dayofyear, dy, y-- 日 
///Day, dd, d -- 日 
///Week, wk, ww -- 周 
///Hour, hh -- 小时 
///minute, mi, n -- 分钟 
///second, ss, s -- 秒 
///millisecond, ms -- 毫秒 
///</param> 
///<param name="beginDate" type="DateTime"> 
///要用于比较我日期 
///</param> 
///<returns type="int"> 
///返回日期差的绝对值。 
///</returns> 
datepart = datepart.toLowerCase(); 
var yearDiff = Math.abs(this.getFullYear() - beginDate.getFullYear()); 
switch (datepart) { 
case "year": 
case "yy": 
case "yyyy": 
return yearDiff; 
case "quarter": 
case "qq": 
case "q": 
var qDiff = 0; 
switch (yearDiff) { 
case 0: 
qDiff = Math.abs(this.getSeason() - beginDate.getSeason()); 
break; 
case 1: 
qDiff = (this.getSeason() - new Date(this.getFullYear(), 0, 1).getSeason()) + 
(new Date(beginDate.getFullYear(), 11, 31).getSeason() - 
beginDate.getSeason()) + 1; 
break; 
default: 
qDiff = (this.getSeason() - new Date(this.getFullYear(), 0, 1).getSeason()) + 
(new Date(beginDate.getFullYear(), 11, 31).getSeason() - 
beginDate.getSeason()) + 1 + (yearDiff - 1) * 4; 
break; 
} 
return qDiff; 
case "month": 
case "mm": 
case "m": 
var monthDiff = 0; 
switch (yearDiff) { 
case 0: 
monthDiff = Math.abs(this.getMonth() - beginDate.getMonth()); 
break; 
case 1: 
monthDiff = (this.getMonth() - new Date(this.getFullYear(), 0, 1).getMonth()) + 
(new Date(beginDate.getFullYear(), 11, 31).getMonth() - 
beginDate.getMonth()) + 1; 
break; 
default: 
monthDiff = (this.getMonth() - new Date(this.getFullYear(), 0, 1).getMonth()) + 
(new Date(beginDate.getFullYear(), 11, 31).getMonth() - 
beginDate.getMonth()) + 1 + (yearDiff - 1) * 12; 
break; 
} 
return monthDiff; 
case "dayofyear": 
case "dy": 
case "y": 
case "day": 
case "dd": 
case "d": 
return Math.abs((this.setHours(0, 0, 0, 0) - beginDate.setHours(0, 0, 0, 0)) / 1000 / 60 / 60 / 24); 
case "week": 
case "wk": 
case "ww": 
var weekDiff = 0; 
switch (yearDiff) { 
case 0: 
weekDiff = Math.abs(this.getWeek() - beginDate.getWeek()); 
break; 
case 1: 
weekDiff = (this.getWeek() - new Date(this.getFullYear(), 0, 1).getWeek()) + 
(new Date(beginDate.getFullYear(), 11, 31).getWeek() - 
beginDate.getWeek()) + 1; 
break; 
default: 
weekDiff = (this.getWeek() - new Date(this.getFullYear(), 0, 1).getWeek()) + 
(new Date(beginDate.getFullYear(), 11, 31).getWeek() - 
beginDate.getWeek()) + 1; 
var thisYear = this.getFullYear(); 
for (var i = 1; i < yearDiff; i++) { 
weekDiff += new Date(thisYear - i, 0, 1).getWeeksOfYear(); 
} 
break; 
} 
return weekDiff; 
case "hour": 
case "hh": 
return Math.abs((this - beginDate) / 1000 / 60 / 60); 
case "minute": 
case "mi": 
case "n": 
return Math.abs((this - beginDate) / 1000 / 60); 
case "second": 
case "ss": 
case "s": 
return Math.abs((this - beginDate) / 1000); 
case "millisecond": 
case "ms": 
return Math.abs(this - beginDate); 
} 
} 
Date.prototype.getFirstWeekDays = function() { 
///<summary> 
///获取当前日期所在年份中第一个星期的天数 
///</summary> 
return (7 - new Date(this.getFullYear(), 0, 1).getDay()); //JS里的月份也是从0开始的,0表示1月,依此类推。 
} 
Date.prototype.getLastWeekDays = function(year) { 
///<summary> 
///获取当前日期所在年份中最后一个星期的天数 
///</summary> 
return (new Date(this.getFullYear(), 11, 31).getDay() + 1); //JS里的月份也是从0开始的,0表示1月,依此类推。 
} 
Date.prototype.getWeeksOfYear = function() { 
///<summary> 
///获取当前日期所在年份的周数 
///</summary> 
return (Math.ceil((new Date(this.getFullYear(), 11, 31, 23, 59, 59) - 
new Date(this.getFullYear(), 0, 1)) / 1000 / 60 / 60 / 24) - 
this.getFirstWeekDays() - this.getLastWeekDays()) / 7 + 2; 
} 
Date.prototype.getSeason = function() { 
///<summary> 
///获取当前日期所在是一年中的第几季。返回一个季度整数值。 
///</summary> 
var month = this.getMonth(); 
switch (month) { 
case 0: 
case 1: 
case 2: 
return 1; 
case 3: 
case 4: 
case 5: 
return 2; 
case 6: 
case 7: 
case 8: 
return 3; 
default: 
return 4; 
} 
} 
Date.prototype.getWeek = function() { 
///<summary> 
///获取当前日期所在是一年中的第几周。返回一个整数值。 
///</summary> 
var firstDate = new Date(this.getFullYear(), 0, 1); 
var firstWeekDays = this.getFirstWeekDays(); 
var secondWeekFirstDate = firstDate.add("dd", firstWeekDays, true); 
var lastDate = new Date(this.getFullYear(), 11, 31); 
var lastWeekDays = this.getLastWeekDays(); 
if (this.dateDiff("day", firstDate) < firstWeekDays) { 
return 1; 
} 
else if (this.dateDiff("day", lastDate) < lastWeekDays) { 
return this.getWeeksOfYear(); 
} 
else { 
return Math.ceil((this - secondWeekFirstDate) / 1000 / 60 / 60 / 24 / 7) + 1; 
} 
}
Javascript 相关文章推荐
Javascript实例教程(19) 使用HoTMetal(5)
Dec 23 Javascript
Javascript 复制数组实现代码
Nov 26 Javascript
ajax的hide隐藏问题解决方法
Dec 11 Javascript
ScrollDown的基本操作示例
Jun 09 Javascript
javascript 实现字符串反转的三种方法
Nov 23 Javascript
浅谈JavaScript的Polymer框架中的事件绑定
Jul 29 Javascript
node中Express 动态设置端口的方法
Aug 04 Javascript
《javascript少儿编程》location术语总结
May 27 Javascript
JS实现可针对算术表达式求值的计算器功能示例
Sep 04 Javascript
vue中导出Excel表格的实现代码
Oct 18 Javascript
小程序两种滚动公告栏的实现方法
Sep 17 Javascript
微信小程序自定义tabbar custom-tab-bar 6s出不来解决方案(cover-view不兼容)
Nov 01 Javascript
Jquery 基础学习笔记之文档处理
May 29 #Javascript
Jquery 基础学习笔记
May 29 #Javascript
javascript AutoScroller 函数类
May 29 #Javascript
关于JavaScript的一些看法
May 27 #Javascript
广告切换效果(缓动切换)
May 27 #Javascript
js 图片缩放(按比例)控制代码
May 27 #Javascript
图片上传即时显示缩略图的js代码
May 27 #Javascript
You might like
php入门之连接mysql数据库的一个类
2012/04/21 PHP
php上传图片到指定位置路径保存到数据库的具体实现
2013/12/30 PHP
JS+PHP实现用户输入数字后显示最大的值及所在位置
2017/06/19 PHP
多个Laravel项目如何共用migrations详解
2018/09/25 PHP
javascript动画效果类封装代码
2007/08/28 Javascript
用js统计用户下载网页所需时间的脚本
2008/10/15 Javascript
JavaScript类库D
2010/10/24 Javascript
jquery的index方法实现tab效果
2011/02/16 Javascript
jQuery知识点整理
2015/01/30 Javascript
js数组去重的方法汇总
2015/07/29 Javascript
总结JavaScript设计模式编程中的享元模式使用
2016/05/21 Javascript
用AngularJS的指令实现tabs切换效果
2016/08/31 Javascript
JS文件上传神器bootstrap fileinput详解
2021/01/28 Javascript
使用Node.js给图片加水印的方法
2016/11/15 Javascript
Json按某个键的值进行排序
2016/12/22 Javascript
angular.js 路由及页面传参示例
2017/02/24 Javascript
简单学习5种处理Vue.js异常的方法
2019/06/17 Javascript
绘制微信小程序验证码功能的实例代码
2021/01/05 Javascript
Vue-router编程式导航的两种实现代码
2021/03/04 Vue.js
python列表的增删改查实例代码
2018/01/30 Python
基于DataFrame筛选数据与loc的用法详解
2018/05/18 Python
对Python中的条件判断、循环以及循环的终止方法详解
2019/02/08 Python
Python正则表达式匹配日期与时间的方法
2019/07/07 Python
Python CVXOPT模块安装及使用解析
2019/08/01 Python
Django通过dwebsocket实现websocket的例子
2019/11/15 Python
Python startswith()和endswith() 方法原理解析
2020/04/28 Python
通过Python实现Payload分离免杀过程详解
2020/07/13 Python
HTML5 CSS3给网站设计带来出色效果
2009/07/16 HTML / CSS
HTML5学习笔记之html5与传统html区别
2016/01/06 HTML / CSS
Foot Locker澳洲官网:美国运动服和鞋类零售商
2019/10/11 全球购物
市场营销工作计划书
2014/09/15 职场文书
单位委托书
2014/10/15 职场文书
出国留学自荐信模板
2015/03/06 职场文书
python lambda 表达式形式分析
2022/04/03 Python
php解析非标准json、非规范json的方式实例
2022/05/10 PHP
React自定义hook的方法
2022/06/25 Javascript