如何在JavaScript日期对象中添加年,月,日,小时,分钟或秒?

时间:2018-11-16 12:45:27

标签: javascript date datetime time date-arithmetic

我经常遇到这样的情况,我想向JavaScript中的Date对象添加年,月,日,小时,分钟或秒。每个 specific “添加”都有许多描述的方法(例如,在添加天,例如),但是我还没有找到关于stackoverflow的完整解决方案,因此我决定在{ {3}}样式。 Q&A是一种无需使用框架即可解决问题的方法。


在评论和答案中建议的其他解决方案:

处理该问题的框架/库:

My own answer(感谢JonnyIrving / Eugene Mihaylin / Pac0)

moment.js(感谢RobG)

https://blog.bitsrc.io/9-javascript-date-time-libraries-for-2018-12d82f37872d(感谢RobG)

特定添加主题的示例(感谢Pac0):

天数:fecha.js

分钟:Add days to JavaScript Date

小时:How to add 30 minutes to a JavaScript Date object?

月份:Adding hours to Javascript Date object?


(我不会将任何答案标记为已接受,因为我认为有多种有效方法)

4 个答案:

答案 0 :(得分:2)

您可能不会倾向于引入库来解决此问题,并且我了解有时最好采用香草库,但就个人而言,我发现在JS中处理日期和时间的所有麻烦变得更加容易您介绍Moment.js库。

您可以在此处查看文档:{​​{3}}

下面,我展示了它在增加时间单位方面可以做什么,但是正如您将从文档中看到的那样,它还可以做更多的工作。例如,在格式化日期对象方面确实很棒。

moment(new Date());

var nowPlusYear = moment().add(1, 'year');
var nowPlusMonth = moment().add(1, 'month');
var nowPlusMinute = moment().add(1, 'minute');

console.log("In 1 year it will be", nowPlusYear);
console.log("In 1 month it will be", nowPlusMonth);
console.log("In 1 minute it will be", nowPlusMinute);
<script src="https://cdn.jsdelivr.net/momentjs/2.10.6/moment-with-locales.min.js"></script>

无论如何都要检查一下,看看您的想法。

希望这会有所帮助!

答案 1 :(得分:0)

尝试摆脱JS约会地狱,并使用广泛使用的moment.js library

moment('2018-01-01').add(1, 'day'); 

moment('2018-01-01').add(1, 'hour');

等...

答案 2 :(得分:0)

您可以使用moment.js

moment('2000-01-01').add(1, 'year');
moment('2000-01-01').add(1, 'month');
moment('2000-01-01').add(1, 'days');
moment('2000-01-01').add(1, 'hour');

或手动进行设置,例如answer

答案 3 :(得分:-4)

我的方法是使用以下添加功能扩展Date.prototype:

Date.prototype.addYears = Date.prototype.addYears || function (y, supressSet) {
    if (!supressSet) { this.setFullYear(this.getFullYear() + y); return this; }
    return new Date(this).addYears(y);
};
Date.prototype.addDays = Date.prototype.addDays || function (d, supressSet) {
    return this.addHours(d * 24, supressSet);
};
Date.prototype.addHours = Date.prototype.addHours || function (h, supressSet) {
    return this.addMinutes(h * 60, supressSet);
};
Date.prototype.addMinutes = Date.prototype.addMinutes || function (m, supressSet) {
    return this.addSeconds(m * 60, supressSet);
};
Date.prototype.addSeconds = Date.prototype.addSeconds || function (s, supressSet) {
    return this.addMilliseconds(s * 1000, supressSet);
};
Date.prototype.addMilliseconds = Date.prototype.addMilliseconds || function (ms, supressSet) {
    if (!supressSet) { this.setTime(this.getTime() + ms); return this; }
    return new Date(this).addMilliseconds(ms);
};

supressSet参数是可选的,使相应的函数可以用作吸气剂,而无需更改对象本身。如果省略,则将其评估为false,这意味着原始日期对象将被修改。

正如评论中指出的那样,我没有考虑到leap年。为此,我花了几个月的时间调整了解决方案JavaScript function to add X months to a date

var DateHelper = {
    isLeapYear: function (year) {
        return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0));
    },
    getDaysInMonth: function (dateinput) {
        return [31, (DateHelper.isLeapYear(dateinput.getFullYear()) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][dateinput.getMonth()];
    }
};

Date.prototype.addMonths = function (m, supressSet) {
    var n = this.getDate(),nDate=new Date(this);
    nDate.setDate(1);
    nDate.setMonth(nDate.getMonth() + m);
    nDate.setDate(Math.min(n, DateHelper.getDaysInMonth(nDate)));
    if (!supressSet) {
        this.setDate(nDate.getDate()); this.setMonth(nDate.getMonth());
    }
    return nDate;
};