首页 > 百科知识 正文

JS利用prototype给时间Date增加常用方法,javascriptdate类型

时间:2024-01-27 02:00:02 阅读:139 作者:做好男

程序开发过程中时常会涉及时间增减操作,原生JS并没有提供时间增量操作函数,利用prototype我们可以轻松给Date类型增加一些时间操作的函数,下面演示下如何给Date增加如下几个方法

1、addMilliseconds方法

2、addSeconds

3、addMinutes

4、addHours

5、addDays

6、addMonths

7、addYears

除了方法6和7规范要传入整数外(非整数将取整计算),其余方法可以传入整数或小数

上代码

JS利用prototype给时间Date增加常用方法,javascriptdate类型-第1张

代码文本

(function(){ Date.prototype.addMilliseconds = function (milliseconds) { return new Date(this.getTime() milliseconds); } Date.prototype.addSeconds = function (seconds) { return new Date(this.getTime() seconds * 1000); } Date.prototype.addMinutes = function (minutes) { return new Date(this.getTime() minutes * 60000); } Date.prototype.addHours = function (hours) { return new Date(this.getTime() hours * 3600000); } Date.prototype.addDays = function (days) { return new Date(this.getTime() days * 86400000); } Date.prototype.addMonths = function (months) { months = Number.parseInt(months); var d = new Date(this); var years = Number.parseInt(months / 12); var leftMonth = months - years * 12; var month = d.getMonth() leftMonth; d.setFullYear(d.getFullYear() years); d.setMonth(month); return d; } Date.prototype.addYears = function (years) { var years = Number.parseInt(years); var d = new Date(this); d.setFullYear(d.getFullYear() years); return d; } })()

看看测试吧

JS利用prototype给时间Date增加常用方法,javascriptdate类型-第2张

发文很辛苦喜欢的点个赞,加个关注,谢谢大家!

版权声明:该问答观点仅代表作者本人。如有侵犯您版权权利请告知 cpumjj@hotmail.com,我们将尽快删除相关内容。