JavaScript Date原型扩展:自定义日期格式化函数实现

作者:拾光时间:2026-10-29 03:30:52浏览:205

本文介绍如何在JavaScript中通过扩展Date对象的prototype来添加Format方法,实现灵活的日期字符串格式化。详细解析了年、月、日、时分秒及星期的正则替换逻辑,并提供完整的代码示例与调用方式,帮助开发者在前端轻松处理日期显示需求。

JavaScript日期格式化需求与原型扩展思路

在前端开发中,经常需要处理日期的格式化显示,而JavaScript原生提供的日期方法相对基础,缺乏后端语言中那样便捷的格式化调用接口。为此,可以通过扩展Date对象的prototype属性,定义一个通用的Format方法,从而简化日常开发中的日期处理工作。

Date.prototype.Format方法实现细节

具体实现代码如下:

首先,在Date原型上增加格式化方法。
Date.prototype.Format = function (formatStr) {
var str = formatStr;
var Week = ['日', '一', '二', '三', '四', '五', '六'];
str = str.replace(/yyyy|YYYY/, this.getFullYear());
 str = str.replace(/yy|YY/, (this.getYear() % 100) > 9 ? (this.getYear() % 100).toString() : '0' + (this.getYear() % 100));
 var month = this.getMonth() + 1;
 str = str.replace(/MM/, month > 9 ? month.toString() : '0' + month);
 str = str.replace(/M/g, month);
str = str.replace(/w|W/g, Week[this.getDay()]);
str = str.replace(/dd|DD/, this.getDate() > 9 ? this.getDate().toString() : '0' + this.getDate());
 str = str.replace(/d|D/g, this.getDate());
str = str.replace(/hh|HH/, this.getHours() > 9 ? this.getHours().toString() : '0' + this.getHours());
 str = str.replace(/h|H/g, this.getHours());
 str = str.replace(/mm/, this.getMinutes() > 9 ? this.getMinutes().toString() : '0' + this.getMinutes());
 str = str.replace(/m/g, this.getMinutes());
str = str.replace(/ss|SS/, this.getSeconds() > 9 ? this.getSeconds().toString() : '0' + this.getSeconds());
 str = str.replace(/s|S/g, this.getSeconds());
 return str;
}

Format方法的实际调用示例

使用该方法的调用过程非常简洁,例如:

具体调用示例代码如下:

var d = new Date();
var str = d.Format("yyyy-MM-dd hh:mm:ss");
console.log(str);
作者最新文章