後台傳來的時間常常是 Long 型時間戳(毫秒數),直接展示給用戶並不友好。下面這套方法通過擴展 Date 對象的 format 方法,把 Long 值靈活轉換成標準的日期字符串。
復制代碼 代碼如下:
<script language="javascript">
// 擴展 Date 的 format 方法
Date.prototype.format = function (format) {
var o = {
"M+": this.getMonth() + 1,
"d+": this.getDate(),
"h+": this.getHours(),
"m+": this.getMinutes(),
"s+": this.getSeconds(),
"q+": Math.floor((this.getMonth() + 3) / 3),
"S": this.getMilliseconds()
}
if (/(y+)/.test(format)) {
format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
}
for (var k in o) {
if (new RegExp("(" + k + ")").test(format)) {
format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
}
}
return format;
}
/**
* 轉換日期對象為日期字符串
* @param date 日期對象
* @param isFull 是否為完整日期,true 時格式如 "2000-03-05 01:05:04",false 時如 "2000-03-05"
*/
function getSmpFormatDate(date, isFull) {
var pattern = "";
if (isFull == true || isFull == undefined) {
pattern = "yyyy-MM-dd hh:mm:ss";
} else {
pattern = "yyyy-MM-dd";
}
return getFormatDate(date, pattern);
}
// 轉換當前日期對象為日期字符串
function getSmpFormatNowDate(isFull) {
return getSmpFormatDate(new Date(), isFull);
}
// 轉換 long 值為日期字符串
function getSmpFormatDateByLong(l, isFull) {
return getSmpFormatDate(new Date(l), isFull);
}
// 按指定格式轉換 long 值
function getFormatDateByLong(l, pattern) {
return getFormatDate(new Date(l), pattern);
}
// 通用格式化方法
function getFormatDate(date, pattern) {
if (date == undefined) {
date = new Date();
}
if (pattern == undefined) {
pattern = "yyyy-MM-dd hh:mm:ss";
}
return date.format(pattern);
}
alert(getSmpFormatDateByLong(1279829423000, false));
</script>
這套封裝的關鍵在於先給 Date 掛上一個通用的 format 方法,再用幾個語義清晰的包裝函數對外提供能力:既能格式化當前時間,也能格式化傳入的 Date 對象或 Long 時間戳,還支持自定義格式串,日常開發中複用起來相當順手。