原文出自:www.hangge.com 原文鏈接:http://www.hangge.com/blog/cache/detail_1346.html
背景
有時我們需要在 javascript 中對日期進行格式化,將其轉換成固定格式的字符串。網上有許多現成的 JS 日期庫可以使用,其實不借助這些庫我們也可以自己實現。
對Date進行擴展
爲方便我們對日期(Date)進行格式化輸出,先對 Date 進行擴展,增加 format 方法。以後調用 Date 對象的 format 方法即可將日期轉換成我們指定格式的字符串(String)。
Date.prototype.format = function (fmt) {
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(fmt)) {
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
}
for (var k in o) {
if (new RegExp("(" + k + ")").test(fmt)) {
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ?
(o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
}
}
return fmt;
}
案例
1、格式化輸出當前時間:
(new Date()).format("yyyy-MM-dd hh:mm:ss.S") // 2019-03-21 17:01:25.928
(new Date()).format("yyyy-M-d h:m:s.S") // 2019-3-21 17:2:37.719
2、格式化輸出指定時間:
var date = new Date("2019-03-31 15:40:16.0");
date.format("MM-dd hh:mm"); //03-31 15:40``
javascript 日期格式化學習:
原文出自:www.hangge.com 原文鏈接:http://www.hangge.com/blog/cache/detail_1346.html