DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> 擴展javascript的Date方法實現代碼(prototype)
擴展javascript的Date方法實現代碼(prototype)
編輯:關於JavaScript     
最近項目的部分功能正在重構,前端也基本上推翻了原來的設計,在之前半年的積累上有了新的方案。這幾天在做前端的重構和設計,遇到了一些問題。因為這個模塊最主要的還是對時間的控制,大量的操作js的Date對象,可是js原生的Date方法太少了,操作起來太不方便。於是打算擴展下Date的prototype。

長期從事C#的開發,被C#影響著我的思維。C#中DateTime的操作就很方便,於是就參考它對js的Date做了擴展。
復制代碼 代碼如下:
//將指定的毫秒數加到此實例的值上
Date.prototype.addMilliseconds = function (value) {
var millisecond = this.getMilliseconds();
this.setMilliseconds(millisecond + value);
return this;
};
//將指定的秒數加到此實例的值上
Date.prototype.addSeconds = function (value) {
var second = this.getSeconds();
this.setSeconds(second + value);
return this;
};
//將指定的分鐘數加到此實例的值上
Date.prototype.addMinutes = function (value) {
var minute = this.addMinutes();
this.setMinutes(minute + value);
return this;
};
//將指定的小時數加到此實例的值上
Date.prototype.addHours = function (value) {
var hour = this.getHours();
this.setHours(hour + value);
return this;
};
//將指定的天數加到此實例的值上
Date.prototype.addDays = function (value) {
var date = this.getDate();
this.setDate(date + value);
return this;
};
//將指定的星期數加到此實例的值上
Date.prototype.addWeeks = function (value) {
return this.addDays(value * 7);
};
//將指定的月份數加到此實例的值上
Date.prototype.addMonths = function (value) {
var month = this.getMonth();
this.setMonth(month + value);
return this;
};
//將指定的年份數加到此實例的值上
Date.prototype.addYears = function (value) {
var year = this.getFullYear();
this.setFullYear(year + value);
return this;
};
//格式化日期顯示 format="yyyy-MM-dd hh:mm:ss";
Date.prototype.format = function (format) {
var o = {
"M+": this.getMonth() + 1, //month
"d+": this.getDate(), //day
"h+": this.getHours(), //hour
"m+": this.getMinutes(), //minute
"s+": this.getSeconds(), //second
"q+": Math.floor((this.getMonth() + 3) / 3), //quarter
"S": this.getMilliseconds() //millisecond
}
if (/(y+)/.test(format)) {
format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
}
for (var k in o) {
if (new RegExp("(" + k + ")").test(format)) {
format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
}
}
return format;
}

使用方法我想應該不用多說了,就是:
復制代碼 代碼如下:
var date = new Date();
date.addHours(1);
date.addYears(2);
document.write(date.format('yyyy-MM-dd hh:mm:ss'));

希望這個擴展方法可以幫助到大家。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved