時間戳和日期格式的互轉是日常開發中的高頻操作,比如接口傳時間戳、頁面展示可讀日期。下面從 Date 構造函數說起,再給出兩個方向的轉換代碼。
最簡單的用法是無參數構造,取當前時間:
var theDate = new Date(); theDate.getDate();
Date 對象有多種構造方式:
new Date() new Date(milliseconds) new Date(datestring) new Date(year, month) new Date(year, month, day) new Date(year, month, day, hours) new Date(year, month, day, hours, minutes) new Date(year, month, day, hours, minutes, seconds) new Date(year, month, day, hours, minutes, seconds, microseconds)
各參數含義:
milliseconds:數字被視為時間戳(毫秒),創建距 1970 年 1 月 1 日指定毫秒的對象。datestring:字符串形式,必須能被 Date.parse() 解析。year 為整數,0–99 會自動加 1900;month 取值 0–11;day 取值 1–31;hours 0–23;minutes 0–59;seconds 0–59;microseconds 0–999。
var d1 = new Date();
var d2 = new Date(1320336000000);
var d3 = new Date("2013-8-20 18:20:30");
var d4 = new Date(2013, 7, 26);
注意 d4 表示的是 2013 年 8 月 26 日,因為月份從 0 計數。
var dateStr = "2013/5/12 20:10:20"; var date = new Date(dateStr); console.log(date.getTime());
getTime() 返回當前時間距 1970 年 1 月 1 日之間的毫秒數,需要用 Date 對象調用:
var myDate = new Date(); console.log(myDate.getTime());
在支持 ES6 的環境裡,Date.now() 更直接;若需要秒級時間戳,除以 1000 並取整即可:Math.floor(Date.now() / 1000)。
var date = new Date(1368360620000); console.log(date.toLocaleString());
toLocaleString() 可根據本地時間把 Date 對象轉換為字符串並返回:
var d = new Date(); console.log(d.toLocaleString());
如果不希望輸出格式隨環境變化,自己格式化更可控:
function formatDate(now) {
var year = now.getFullYear();
var month = now.getMonth() + 1;
var date = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
}
var d = new Date(1368360620000);
console.log(formatDate(d));
上面的版本在月日時分秒小於 10 時不會補零,實戰中建議補一個輔助函數:
function pad(n) { return n < 10 ? '0' + n : '' + n; }
另外提醒兩點:toLocaleString() 的具體格式依賴於瀏覽器與系統語言設置,若結果要給接口或做字符串比較,請勿依賴它;解析字符串日期時,"2013/5/12" 這類斜槓格式在各大瀏覽器兼容性最好,而 "2013-05-12" 在部分老瀏覽器(尤其 IE)中會返回 Invalid Date,需注意區分。