JavaScript 实现日期灵活格式化的方法

作者:小满时间:2026-10-27 12:27:55浏览:328

本文介绍了如何在 JavaScript 中通过扩展 Date.prototype 实现灵活的日期格式化功能。代码示例展示了如何定义格式字符串(如 YYYY-MM-dd hh:mm:ss),并利用正则表达式匹配和替换,将年、月、日、时、分、秒及季度等时间组件转换为指定格式,适用于前端开发中的时间显示需求。

JavaScript 日期格式化实现

具体实现代码如下所示:

/** 
该代码主要用于对时间对象进行格式化操作;
 */ 
Date.prototype.format = function(format) {
    /* 
例如: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;
}
作者最新文章