JavaScript 扩展 Date 对象实现时间格式化

作者:开源拾贝

时间:2026-10-27

浏览:560

本文介绍如何在 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");

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章