亲宝软件园·资讯

展开

Javascript 日期对象Date扩展方法

人气:0
今天在网上摘抄了些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": //計算時差
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("時差: "+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 -- 月
//https://img.qb5200.com/download-x/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 -- 月
//https://img.qb5200.com/download-x/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;
}
}

加载全部内容

相关教程
猜你喜欢
用户评论