本文介绍如何在 JavaScript 中通过扩展 Date.prototype 实现自定义时间格式化功能。提供了完整的代码示例,展示如何将日期对象转换为指定格式的字符串,如年月日时分秒,并包含实际调用示例。
JavaScript Date 格式化实现
以下是相关代码实现。
/**
此部分用于定义时间对象的格式化方法。
*/
Date.prototype.format = function(format) {
/*
例如,格式参数可以设置为 "YYYY-MM-dd hh:mm:ss"。
*/
var o = {
"M+" :this.getMonth() + 1, // month
"d+" :this.getDate(), // day
"h+" :this.getHours(), // hour
"m+" :this.getMinutes(), // minute
"s+" :this.getSeconds(), // second
"q+" :Math.floor((this.getMonth() + 3) / 3), // quarter
"S" :this.getMilliseconds()
// millisecond
}
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;
}
以下是具体的调用示例代码。
var now = new Date().format("yyyy-MM-dd hh:mm:ss");
另一个示例代码如下。
new Date().format("yy-MM-dd hh:mm");