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 相关文章推荐
JS操作xml对象转换为Json对象示例
Mar 25 Javascript
Node.js v8.0.0正式发布!看看带来了哪些主要新特性
Jun 02 Javascript
easyui datagrid 表格中操作栏 按钮图标不显示的解决方法
Jul 27 Javascript
Vue动态组件实例解析
Aug 20 Javascript
Angular6笔记之封装http的示例代码
Jul 27 Javascript
微信小程序wepy框架笔记小结
Aug 08 Javascript
vue悬浮可拖拽悬浮按钮的实例代码
Aug 20 Javascript
layui使用button按钮 点击出现弹层 弹层中加载表单的实例
Sep 04 Javascript
JS实现点星星消除小游戏
Mar 24 Javascript
antdesign-vue结合sortablejs实现两个table相互拖拽排序功能
Jan 08 Vue.js
浅谈JS的原型和原型链
Jun 04 Javascript
微信小程序实现聊天室功能
Jun 14 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中使用Oracle数据库(5)
2006/10/09 PHP
PHP连接SQLServer2005 的问题解决方法
2010/07/19 PHP
浅析echo(),print(),print_r(),return之间的区别
2013/11/27 PHP
PHP基于redis计数器类定义与用法示例
2018/02/08 PHP
PHP多维数组指定多字段排序的示例代码
2018/05/16 PHP
在JavaScript中使用inline函数的问题
2007/03/08 Javascript
Packer 3.0 JS压缩及混淆工具 下载
2007/05/03 Javascript
JavaScript 读取元素的CSS信息的代码
2010/02/07 Javascript
基于jquery的checkbox下拉框插件代码
2010/06/25 Javascript
jquery中的事件处理详细介绍
2013/06/24 Javascript
JS操作CSS随机改变网页背景实现思路
2014/03/10 Javascript
jquery如何判断表格同一列不同行input数据是否重复
2014/05/14 Javascript
初步认识JavaScript函数库jQuery
2015/06/18 Javascript
Bootstrap幻灯片轮播图支持触屏左右手势滑动的实现方法
2016/10/13 Javascript
微信小程序 页面滑动事件的实例详解
2017/10/12 Javascript
Vue2.0学习之详解Vue 组件及父子组件通信
2017/12/12 Javascript
基于jQuery使用Ajax动态执行模糊查询功能
2018/07/05 jQuery
AngularJs1.x自定义指令独立作用域的函数传入参数方法
2018/10/09 Javascript
jquery的$().each和$.each的区别
2019/01/18 jQuery
react写一个select组件的实现代码
2019/04/03 Javascript
Windows下安装 node 的版本控制工具 nvm
2020/02/06 Javascript
python类型强制转换long to int的代码
2013/02/10 Python
利用python代码写的12306订票代码
2015/12/20 Python
详解python 发送邮件实例代码
2016/12/22 Python
对python中raw_input()和input()的用法详解
2018/04/22 Python
python3 线性回归验证方法
2019/07/09 Python
python读文件的步骤
2019/10/08 Python
Python 3.6打包成EXE可执行程序的实现
2019/10/18 Python
突袭HTML5之Javascript API扩展3—本地存储全新体验
2013/01/31 HTML / CSS
美国著名手表网站:Timepiece
2017/11/15 全球购物
HomeAway的巴西品牌:Alugue Temporada
2018/04/10 全球购物
英国创新设计文具、卡片和礼品包装网站:Paperchase
2018/07/14 全球购物
NOTINO英国:在线购买美容和香水
2020/02/25 全球购物
蓬莱阁导游词
2015/02/04 职场文书
python flappy bird小游戏分步实现流程
2022/02/15 Python
SQL语句中EXISTS的详细用法大全
2022/06/25 MySQL