處理日期與時間是開發中經常遇到的需求。先來看 Date 物件最常用的取值方法:
var myDate = new Date(); myDate.getYear(); // 當前年份(2位) myDate.getFullYear(); // 完整年份(4位) myDate.getMonth(); // 當前月份(0-11,0代表1月) myDate.getDate(); // 當前日(1-31) myDate.getDay(); // 當前星期(0-6,0代表週日) myDate.getTime(); // 從1970.1.1至今的毫秒數 myDate.getHours(); // 當前小時(0-23) myDate.getMinutes(); // 當前分鐘(0-59) myDate.getSeconds(); // 當前秒數(0-59) myDate.getMilliseconds(); // 當前毫秒(0-999) myDate.toLocaleDateString(); // 當前日期 myDate.toLocaleTimeString(); // 當前時間 myDate.toLocaleString(); // 日期與時間
透過擴展 Date.prototype,我們可以為日期加入格式化、閏年判斷、日期計算等實用方法:
// 判斷閏年
Date.prototype.isLeapYear = function () {
return (0 == this.getYear() % 4 && ((this.getYear() % 100 != 0) || (this.getYear() % 400 == 0)));
};
// 日期格式化,支援 YYYY/MM/dd/hh/mm/ss 等佔位符
Date.prototype.Format = function (formatStr) {
var str = formatStr;
var Week = ['日', '一', '二', '三', '四', '五', '六'];
str = str.replace(/yyyy|YYYY/, this.getFullYear());
str = str.replace(/MM/, this.getMonth() > 9 ? this.getMonth().toString() : '0' + this.getMonth());
str = str.replace(/M/g, this.getMonth());
str = str.replace(/w|W/g, Week[this.getDay()]);
str = str.replace(/dd|DD/, this.getDate() > 9 ? this.getDate().toString() : '0' + this.getDate());
str = str.replace(/d|D/g, this.getDate());
str = str.replace(/hh|HH/, this.getHours() > 9 ? this.getHours().toString() : '0' + this.getHours());
str = str.replace(/h|H/g, this.getHours());
str = str.replace(/mm/, this.getMinutes() > 9 ? this.getMinutes().toString() : '0' + this.getMinutes());
str = str.replace(/m/g, this.getMinutes());
str = str.replace(/ss|SS/, this.getSeconds() > 9 ? this.getSeconds().toString() : '0' + this.getSeconds());
str = str.replace(/s|S/g, this.getSeconds());
return str;
};
若要輸出如 2009-06-12 12:00 的格式,可以自己拼字串,並對個位數補零:
function CurentTime() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth() + 1;
var day = now.getDate();
var hh = now.getHours();
var mm = now.getMinutes();
var clock = year + "-";
if (month < 10) clock += "0";
clock += month + "-";
if (day < 10) clock += "0";
clock += day + " ";
if (hh < 10) clock += "0";
clock += hh + ":";
if (mm < 10) clock += "0";
clock += mm;
return clock;
}
此外還可擴展日期相減求天數差、日期加減(DateAdd)、日期差比較(DateDiff)、月份最大天數、一年中的第幾週等方法,形成一套完整的日期工具庫。