日期格式化是前端開發裡的高頻需求:列表要顯示「2014-07-27 09:26」,接口要傳時間戳,社交場景又要顯示「3 分鐘前」。本文整理五種常用思路,從最原始的手工拼接,一直講到可複用的原型擴展與個性化相對時間輸出。
最直觀的方式是用 Date 的 get 系列方法逐段取值,星期則靠 getDay() 的返回值查表。
function syncTime() {
var mydate = new Date();
var week;
switch (mydate.getDay()) {
case 1: week = "星期一"; break;
case 2: week = "星期二"; break;
case 3: week = "星期三"; break;
case 4: week = "星期四"; break;
case 5: week = "星期五"; break;
case 6: week = "星期六"; break;
default: week = "星期天";
}
var str = mydate.getFullYear() + " 年 " + (mydate.getMonth() + 1) +
" 月 " + mydate.getDate() + " 日 " + week;
return str;
}
注意 getMonth() 的返回值從 0 開始,必須 +1 才是真實月份——這是最常見的初學陷阱。這種寫法勝在零依賴、意圖清晰,缺點是格式一旦變化就要改代碼。
JavaScript 的 Date 對象自帶一批格式化與解析方法,適合快速取得標準格式的輸出:
var date = new Date();
date.toDateString(); // Thu Jan 08 2015
date.toTimeString(); // 01:39:08 GMT+0800 (中國標準時間)
date.toLocaleDateString(); // 2015年1月8日
date.toLocaleTimeString(); // 上午1:39:08
date.toUTCString(); // Wed, 07 Jan 2015 17:39:08 GMT
Date.parse('6/10/2014'); // 1402329600000(毫秒數)
Date.parse('Thu Jan 08 2015 01:25:53'); // 1420651553000
Date.parse(); // NaN
Date.UTC(); // NaN
需要提醒的是,Date.parse 與 Date.UTC 在不傳參數時返回 NaN,且各瀏覽器對日期字符串格式的容忍度差異不小,跨環境使用時建議統一採用 YYYY-MM-DD HH:mm:ss 這類較通用的寫法。
把格式化邏輯掛到 Date.prototype 上,用佔位符替換的方式支持自定義模板,是最經典的做法:
Date.prototype.Format = function (formatStr) {
var str = formatStr;
var Week = ['日', '一', '二', '三', '四', '五', '六'];
str = str.replace(/yyyy|YYYY/, this.getFullYear());
str = str.replace(/yy|YY/, (this.getYear() % 100) > 9
? (this.getYear() % 100).toString() : '0' + (this.getYear() % 100));
str = str.replace(/MM/, (this.getMonth() + 1) > 9
? (this.getMonth() + 1).toString() : '0' + (this.getMonth() + 1));
str = str.replace(/M/g, this.getMonth() + 1);
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;
};
使用時只需 new Date().Format('yyyy-MM-dd hh:mm:ss')。這種方案的好處是模板與數據分離,改格式不用改邏輯;需要注意的是直接修改內建原型在多人協作的大型項目中容易引發命名衝突,更穩妥的做法是封裝成獨立工具函數。
如果項目需要同時輸出中文與英文格式、還要帶毫秒,可以借鑒下面這種「先收集時間片段,再按模板替換」的思路:
Date.prototype.toString = function (format, loc) {
var time = {};
time.Year = this.getFullYear();
time.TYear = ("" + time.Year).substr(2);
time.Month = this.getMonth() + 1;
time.TMonth = time.Month < 10 ? "0" + time.Month : time.Month;
time.Day = this.getDate();
time.TDay = time.Day < 10 ? "0" + time.Day : time.Day;
time.Hour = this.getHours();
time.THour = time.Hour < 10 ? "0" + time.Hour : time.Hour;
time.Minute = this.getMinutes();
time.TMinute = time.Minute < 10 ? "0" + time.Minute : time.Minute;
time.Second = this.getSeconds();
time.TSecond = time.Second < 10 ? "0" + time.Second : time.Second;
time.Millisecond = this.getMilliseconds();
time.Week = this.getDay();
var MMMArrEn = ["Jan","Feb","Mar","Apr","May","Jun",
"Jul","Aug","Sep","Oct","Nov","Dec"];
var MMMArr = ["一月","二月","三月","四月","五月","六月",
"七月","八月","九月","十月","十一月","十二月"];
var WeekArrEn = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
var WeekArr = ["星期日","星期一","星期二","星期三","星期四","星期五","星期六"];
if (format != undefined && format.replace(/s/g, "").length > 0) {
if (loc == "en") { MMMArr = MMMArrEn.slice(0); WeekArr = WeekArrEn.slice(0); }
format = format
.replace(/yyyy/ig, time.Year).replace(/yy/ig, time.TYear)
.replace(/MMM/g, MMMArr[time.Month - 1]).replace(/MM/g, time.TMonth)
.replace(/M/g, time.Month)
.replace(/dd/ig, time.TDay).replace(/d/ig, time.Day)
.replace(/HH/g, time.THour).replace(/H/g, time.Hour)
.replace(/mm/g, time.TMinute).replace(/m/g, time.Minute)
.replace(/ss/ig, time.TSecond).replace(/s/ig, time.Second)
.replace(/fff/ig, time.Millisecond)
.replace(/EEE/g, WeekArr[time.Week]);
} else {
format = time.Year + "-" + time.Month + "-" + time.Day + " " +
time.Hour + ":" + time.Minute + ":" + time.Second;
}
return format;
};
// 調用示例
console.log(new Date().toString("yyyy-MM-dd HH:mm:ss")); // 2014-07-27 09:26:52
console.log(new Date().toString("yyyy年MM月dd日 HH:mm:ss")); // 2014年07月27日 09:26:52
console.log(new Date().toString("yyyy年 MMM dd EEE")); // 2014年 七月 27 星期五
console.log(new Date().toString("yyyy MMM dd EEE", "en")); // 2014 Jul 27 Fri
這種實現覆蓋了 12 小時制、英文月份縮寫、星期與毫秒等場景,靈活度最高。不過直接覆寫 toString 會影響所有依賴默認字符串的日誌與調試輸出,工程實踐中更建議另起方法名。
社交類產品很少直接甩出「2014-07-27 09:26」,而是按時間間隔分層展示,這也是實戰中最常用的一種:
/*
* 1、間隔 < 60 秒,顯示「剛剛」
* 2、1 分鐘 ~ 60 分鐘,顯示「XX 分鐘前」
* 3、60 分鐘 ~ 24 小時,顯示「今天 HH:mm」
* 4、1 天 ~ 1 年,顯示「XX月XX日 HH:mm」
* 5、超過 1 年,顯示「XXXX年XX月XX日 HH:mm」
*/
function timeFormat(time) {
var date = new Date(time), curDate = new Date();
var year = date.getFullYear(), month = date.getMonth() + 1, day = date.getDate();
var hour = date.getHours(), minute = date.getMinutes();
var curYear = curDate.getFullYear(), curHour = curDate.getHours();
var timeStr;
if (year < curYear) {
timeStr = year + '年' + month + '月' + day + '日 ' + hour + ':' + minute;
} else {
var pastH = (curDate - date) / 3600000;
if (pastH > curHour) {
timeStr = month + '月' + day + '日 ' + hour + ':' + minute;
} else if (pastH >= 1) {
timeStr = '今天 ' + hour + ':' + minute;
} else {
var pastM = curDate.getMinutes() - minute;
timeStr = pastM > 1 ? pastM + '分鐘前' : '剛剛';
}
}
return timeStr;
}
這段代碼的判斷層級清晰,覆蓋了絕大多數信息流的時間展示需求。如果要更嚴謹,可以再補上「昨天 HH:mm」這一檔,並用絕對時間戳差值(而非 getMinutes() 相減)來計算分鐘數,避免跨小時時出現負數。
format(date, pattern) 工具函數,比污染原型更安全。五種做法並不存在絕對優劣,關鍵是格式需求與項目規模的匹配程度。實際開發中,把可配置、可測試、不污染全局作為取捨標準,通常不會出錯。