JavaScript Date原型扩展:实现C#风格的时间加减与格式化

作者:键盘侠时间:2026-10-25 13:56:41浏览:136

本文介绍如何参考C# DateTime特性,通过扩展JavaScript的Date.prototype来增强原生日期处理能力。实现了addMilliseconds至addYears等时间单位加减方法,以及支持yyyy-MM-dd格式的自定义日期格式化功能,旨在解决原生Date方法不足的问题,提升前端时间处理效率。

扩展背景与目标

近期项目功能重构,前端设计全面更新,基于半年积累提出新方案。在开发过程中,核心需求涉及大量时间控制操作,但JavaScript原生Date对象方法有限,操作不便,因此决定扩展Date原型。



受长期C#开发思维影响,参考C#中便捷的DateTime操作,对JavaScript Date进行了相应扩展。


时间加减方法实现

具体实现代码如下:

 
//将指定的毫秒数加到此实例的值上
Date.prototype.addMilliseconds = function (value) {
var millisecond = this.getMilliseconds();
this.setMilliseconds(millisecond + value);
return this;
}; 
//将指定的秒数加到此实例的值上
Date.prototype.addSeconds = function (value) {
var second = this.getSeconds();
this.setSeconds(second + value);
return this;
}; 
//将指定的分钟数加到此实例的值上
Date.prototype.addMinutes = function (value) {
var minute = this.addMinutes();
this.setMinutes(minute + value);
return this;
}; 
//将指定的小时数加到此实例的值上
Date.prototype.addHours = function (value) {
var hour = this.getHours();
this.setHours(hour + value);
return this;
}; 
//将指定的天数加到此实例的值上
Date.prototype.addDays = function (value) {
var date = this.getDate();
this.setDate(date + value);
return this;
}; 
//将指定的星期数加到此实例的值上
Date.prototype.addWeeks = function (value) {
return this.addDays(value * 7);
}; 
//将指定的月份数加到此实例的值上
Date.prototype.addMonths = function (value) {
var month = this.getMonth();
this.setMonth(month + value);
return this;
}; 
//将指定的年份数加到此实例的值上
Date.prototype.addYears = function (value) {
var year = this.getFullYear();
this.setFullYear(year + value);
return this;
}; 
日期格式化功能//格式化日期显示 format="yyyy-MM-dd hh:mm:ss";
Date.prototype.format = function (format) {
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 date = new Date();
date.addHours(1);
date.addYears(2);
document.write(date.format('yyyy-MM-dd hh:mm:ss'));

希望此扩展方法能对开发者有所帮助。

作者最新文章