How to add 30 minutes to a JavaScript Date object?

2018-12-31 07:25发布

I'd like to get a Date object which is 30 minutes later than another Date object. How do I do it with JavaScript?

13条回答
有味是清欢
2楼-- · 2018-12-31 07:28

For the lazy like myself:

Kip's answer (from above) in coffeescript, using an "enum", and operating on the same object:

Date.UNIT =
  YEAR: 0
  QUARTER: 1
  MONTH: 2
  WEEK: 3
  DAY: 4
  HOUR: 5
  MINUTE: 6
  SECOND: 7
Date::add = (unit, quantity) ->
  switch unit
    when Date.UNIT.YEAR then @setFullYear(@getFullYear() + quantity)
    when Date.UNIT.QUARTER then @setMonth(@getMonth() + (3 * quantity))
    when Date.UNIT.MONTH then @setMonth(@getMonth() + quantity)
    when Date.UNIT.WEEK then @setDate(@getDate() + (7 * quantity))
    when Date.UNIT.DAY then @setDate(@getDate() + quantity)
    when Date.UNIT.HOUR then @setTime(@getTime() + (3600000 * quantity))
    when Date.UNIT.MINUTE then @setTime(@getTime() + (60000 * quantity))
    when Date.UNIT.SECOND then @setTime(@getTime() + (1000 * quantity))
    else throw new Error "Unrecognized unit provided"
  @ # for chaining
查看更多
ら面具成の殇う
3楼-- · 2018-12-31 07:30

Using a Library

If you are doing a lot of date work, you may want to look into JavaScript date libraries like Datejs or Moment.js. For example, with Moment.js, this is simply:

var newDateObj = moment(oldDateObj).add(30, 'm').toDate();

Vanilla Javascript

This is like chaos's answer, but in one line:

var newDateObj = new Date(oldDateObj.getTime() + diff*60000);

Where diff is the difference in minutes you want from oldDateObj's time. It can even be negative.

Or as a reusable function, if you need to do this in multiple places:

function addMinutes(date, minutes) {
    return new Date(date.getTime() + minutes*60000);
}

Be Careful with Vanilla Javascript. Dates Are Hard!

You may think you can add 24 hours to a date to get tomorrow's date, right? Wrong!

addMinutes(myDate, 60*24); //DO NOT DO THIS

It turns out, if the user observes daylight saving time, a day is not necessarily 24 hours long. There is one day a year that is only 23 hours long, and one day a year that is 25 hours long. For example, in most of the United States and Canada, 24 hours after midnight, Nov 2, 2014, is still Nov 2:

addMinutes(new Date('2014-11-02'), 60*24); //In USA, prints 11pm on Nov 2, not 12am Nov 3!

This is why using one of the afore-mentioned libraries is a safer bet if you have to do a lot of work with this.

Below is a more generic version of this function that I wrote. I'd still recommend using a library, but that may be overkill/impossible for your project. The syntax is modeled after MySQL DATE_ADD function.

/**
 * Adds time to a date. Modelled after MySQL DATE_ADD function.
 * Example: dateAdd(new Date(), 'minute', 30)  //returns 30 minutes from now.
 * https://stackoverflow.com/a/1214753/18511
 * 
 * @param date  Date to start with
 * @param interval  One of: year, quarter, month, week, day, hour, minute, second
 * @param units  Number of units of the given interval to add.
 */
function dateAdd(date, interval, units) {
  var ret = new Date(date); //don't change original date
  var checkRollover = function() { if(ret.getDate() != date.getDate()) ret.setDate(0);};
  switch(interval.toLowerCase()) {
    case 'year'   :  ret.setFullYear(ret.getFullYear() + units); checkRollover();  break;
    case 'quarter':  ret.setMonth(ret.getMonth() + 3*units); checkRollover();  break;
    case 'month'  :  ret.setMonth(ret.getMonth() + units); checkRollover();  break;
    case 'week'   :  ret.setDate(ret.getDate() + 7*units);  break;
    case 'day'    :  ret.setDate(ret.getDate() + units);  break;
    case 'hour'   :  ret.setTime(ret.getTime() + units*3600000);  break;
    case 'minute' :  ret.setTime(ret.getTime() + units*60000);  break;
    case 'second' :  ret.setTime(ret.getTime() + units*1000);  break;
    default       :  ret = undefined;  break;
  }
  return ret;
}

Working jsFiddle demo.

查看更多
后来的你喜欢了谁
4楼-- · 2018-12-31 07:34
var newDateObj = new Date();
newDateObj.setTime(oldDateObj.getTime() + (30 * 60 * 1000));
查看更多
宁负流年不负卿
5楼-- · 2018-12-31 07:38
var now = new Date();
now.setMinutes(now.getMinutes() + 30);
查看更多
素衣白纱
6楼-- · 2018-12-31 07:38

This is what I do which seems to work quite well:

Date.prototype.addMinutes = function(minutes) {
    var copiedDate = new Date(this.getTime());
    return new Date(copiedDate.getTime() + minutes * 60000);
}

Then you can just call this like this:

var now = new Date();
console.log(now.addMinutes(50));
查看更多
回忆,回不去的记忆
7楼-- · 2018-12-31 07:40

I always create 7 functions, to work with date in JS: addSeconds, addMinutes, addHours, addDays, addWeeks, addMonths, addYears.

You can see an example here: http://jsfiddle.net/tiagoajacobi/YHA8x/

How to use:

var now = new Date();
console.log(now.addMinutes(30));
console.log(now.addWeeks(3));

This are the functions:

        Date.prototype.addSeconds = function(seconds) {
            this.setSeconds(this.getSeconds() + seconds);
            return this;
        };

        Date.prototype.addMinutes = function(minutes) {
            this.setMinutes(this.getMinutes() + minutes);
            return this;
        };

        Date.prototype.addHours = function(hours) {
            this.setHours(this.getHours() + hours);
            return this;
        };

        Date.prototype.addDays = function(days) {
            this.setDate(this.getDate() + days);
            return this;
        };

        Date.prototype.addWeeks = function(weeks) {
            this.addDays(weeks*7);
            return this;
        };

        Date.prototype.addMonths = function (months) {
            var dt = this.getDate();

            this.setMonth(this.getMonth() + months);
            var currDt = this.getDate();

            if (dt !== currDt) {  
                this.addDays(-currDt);
            }

            return this;
        };

        Date.prototype.addYears = function(years) {
            var dt = this.getDate();

            this.setFullYear(this.getFullYear() + years);

            var currDt = this.getDate();

            if (dt !== currDt) {  
                this.addDays(-currDt);
            }

            return this;
        };
查看更多
登录 后发表回答