時間和日期在電腦與網路上的呈現方式五花八門。開機時有時間顯示,有些網頁也會秀出開啟時間或即時時鐘。做出來其實不難,用 JavaScript 就能搞定。
這個寫法擴充了 Date 物件,讓你可以用字串模板決定輸出格式:
Date.prototype.format = function (format){
if (format == null) format = "yyyy/MM/dd HH:mm:ss.SSS";
var year = this.getFullYear();
var month = this.getMonth();
var sMonth = ["January","February","March","April","May","June","July","August","September","October","November","December"][month];
var date = this.getDate();
var day = this.getDay();
var hr = this.getHours();
var min = this.getMinutes();
var sec = this.getSeconds();
var daysInYear = Math.ceil((this - new Date(year,0,0))/86400000);
var weekInYear = Math.ceil((daysInYear + new Date(year,0,1).getDay())/7);
var weekInMonth = Math.ceil((date + new Date(year,month,1).getDay())/7);
return format.replace("yyyy",year)
.replace("yy",year.toString().substr(2))
.replace("dd",(date<10?"0":"")+date)
.replace("HH",(hr<10?"0":"")+hr)
.replace("mm",(min<10?"0":"")+min)
.replace("ss",(sec<10?"0":"")+sec)
.replace("SSS",this%1000)
.replace("a",(hr<12?"AM":"PM"))
.replace(/E/g,["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][day])
.replace("D",daysInYear)
.replace("w",weekInYear)
.replace(/MMMM+/,sMonth)
.replace("MMM",sMonth.substring(0,3))
.replace("MM",(month<9?"0":"")+(month+1));
}
它的邏輯很直白:先把各個時間成分取出來,再依序替換模板中的佔位符。yyyy 是四位年、MM 是月份、dd 是日、HH 是 24 小時制、mm 分、ss 秒、SSS 毫秒、E 是星期、D 是當年第幾天、w 是當年第幾週。
呼叫方式:
var d = new Date();
alert(d.format()); // 預設格式
alert(d.format("MM-dd-yyyy"));
alert(d.format("dd/MM/yy"));
alert(d.format("yyyy年MM月dd日 HH時mm分ss.SSS秒"));
alert(d.format("yyyy年MM月dd日 E HH時mm分ss.SSS秒"));
alert(d.format("yyyy年MM月dd日 E 今年的第D天,第w周,MMMM這個月的第W周"));
想把「2026年8月27日」顯示成「二零二六年八月二十七日」,可以這樣寫:
String.prototype.toCHS = function(){
return this.replace(/\d/g, function(a){
return "零一二三四五六七八九".charAt(parseInt(a));
});
}
Number.prototype.toCHS = function(){
return ((this>19 ? Math.floor(this/10) : "") +
(this>9 ? "十" : "") +
(this%10==0 && this>0 ? "" : this%10)).toCHS();
}
Date.prototype.toCHS = function(){
with(this) return (getFullYear()+"").toCHS() + "年"
+ (getMonth()+1).toCHS() + "月"
+ getDate().toCHS() + "日"
+ getHours().toCHS() + "時"
+ getMinutes().toCHS() + "分"
+ getSeconds().toCHS() + "秒";
}
alert(new Date().toCHS());
這裡用了三層擴充:String 版負責把阿拉伯數字逐字換成中文數字,Number 版負責處理「二十」「三十」這類十位數的讀法,Date 版則把年月日時分秒拼成完整句子。
實務上還有一個更省事的做法:用 toLocaleString() 搭配 Intl.DateTimeFormat,瀏覽器本身就能輸出各語言與各國格式的日期,不必自己維護模板。