今天記錄一種使用正則表達式將時間戳(如“1469261964000”)轉換為 yyyy-MM-dd hh:mm 格式時間(如“2018-12-6 15:27”)的方法。
一、背景知識
先介紹一些相關知識點。
- 時間戳
此處指 JS 時間戳,是當前時間到 1970年1月1日00:00:00 UTC 對應的毫秒數(shù),和 unix 時間戳并非同一概念(表示秒數(shù))。
- 正則表達式
參考 廖雪峰-正則表達式
正則中用"()"括起來的部分表示子串(分組);
$1表示第一個子串中的內(nèi)容,$2表示第二個,依此類推...
二、具體實現(xiàn)
function farmatDate(time, fmt) {
if (/(y+)/.test(fmt) {
fmt = fmt.replace(RegExp.$1, date.getFullYear() + '').substr(4 - RegExp.$1.length);
}
let o = {
'M+': getMonth() + 1,
'd+': getDay(),
'h+': getHours(),
'm+': getMinutes(),
's+': getSeconds()
};
for (let key in o) {
if(RegExp(`(${key})`.test(fmt)) {
let str = o[key] + '';
fmt = fmt.replace(RegExp.$1, str.length === 2 ? str:padLeftZero(str);
}
}
return fmt;
}
// 函數(shù) padLeftZero 的作用:如果月份為1位(如9),則在其左邊補0(變?yōu)?9)
function padLeftZero(str) {
return '00' + substr(str.length);
}
// 舉例
let res = formatDate('1469261964000', 'yyyy-MM-dd hh:mm');
console.log(res); // 2016-07-06 16:19