四时宝库

程序员的知识宝库

JS利用prototype给时间(Date)增加常用方法

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

1、addMilliseconds方法

2、addSeconds

3、addMinutes

4、addHours

5、addDays

6、addMonths

7、addYears

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

上代码

代码文本

(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;
    }
})()

看看测试吧

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

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言
    友情链接