Javascript 日期對象Date擴充方法

來源:互聯網
上載者:User

今天在網上摘抄了些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 -- 月
///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;
}
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.