1130

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

Liam
  • 27,717
  • 28
  • 128
  • 190
Morgan Cheng
  • 73,950
  • 66
  • 171
  • 230
  • See also http://stackoverflow.com/questions/674721/how-do-i-subtract-minutes-from-a-date-in-javascript – David d C e Freitas May 21 '11 at 15:12
  • 1
    I built a little calendar popup script in js, its on [Github](http://github.com/cbiggins/calendar/tree/master), maybe look through the code to see how the date object is interected with. Also, check [Javascript Kit](http://www.javascriptkit.com/jsref/) as its an awesome js reference, especially for the date object. – Christian Jul 29 '09 at 03:44
  • 4
    All answers below that use a variation of ```date.setMinutes(date.getMinutes() + ...)``` will fail crossing over Daylight Saving boundaries. For example (assuming '2014-03-09' is a Daylight Saving boundary): ```var d = new Date('2014-03-09 01:59:00'), f = new Date(d.getTime()); d.setMinutes(d.getMinutes() + 30);``` ```d``` is now 30 minutes earlier, not later, than ```f```. – Spig Sep 12 '14 at 15:07
  • 1
    @Spig: 30 minutes after 1:59 AM on DST boundary is 1:29AM. There is no error. If you print `f` and `d`, you'll see one says "GMT-0500" the other says "GMT-0400" (or whatever your time zone is). Also, if you call `.getTime()` on both `f` and `d`, you'll see that `f` is larger than `d` (i.e. later). – Kip Sep 16 '14 at 14:24
  • @Kip: On Chrome if I add a ```console.log(d, d.getTime(), '---', f, f.getTime())``` to my original string, the output is ```Sun Mar 09 2014 01:29:00 GMT-0500 (EST) 1394346540000 " --- " Sun Mar 09 2014 01:59:00 GMT-0500 (EST) 1394348340000```. EST does not roll over to EDT. ```f``` should be *smaller* than ```d``` since I added 30 minutes to ```d```, not the other way around. – Spig Sep 17 '14 at 15:23
  • 1
    @Spig: interesting, tried it on Firefox and it worked. I think it falls into a grey area in the specification of how getMinutes() should work. `01:89` would become `02:29`, which doesn't exist on the day you "spring forward". Chrome decides that should be `01:29`, FF decides on `03:29`. On the night when you "fall back", both browsers skip the "fall back" hour and jump ahead by 90 minutes, to `02:29`. Here are some JSFiddle demos: ["spring forward"](http://jsfiddle.net/uj9462vp/6/) / ["fall back"](http://jsfiddle.net/5zLzsnsf/4/) – Kip Sep 17 '14 at 17:05
  • @Spig: FWIW, my top-voted answer has always worked fine in this case. :) It uses getTime() and setTime(), so it is based on unix timestamp (which doesn't care about DST) – Kip Sep 17 '14 at 17:06
  • @MorganCheng: Could you accept my answer if you think it's the best? This is by far my most popular answer but it is not the accepted answer. :) – Kip Nov 06 '14 at 16:00
  • Could be possible that you guys verify the correct answer? – eMarine Oct 15 '15 at 17:33
  • Consider marking an answer as accepted – Alex May 25 '16 at 13:15
  • 2
    If one of the answers below answered your question, the way this site works works, you'd "accept" the answer, more here: ***[What should I do when someone answers my question?](http://stackoverflow.com/help/someone-answers)***. But only if your question really has been answered. If not, consider adding more details to the question. – Blue Jul 13 '17 at 21:32

29 Answers29

1307

Using a Library

If you are doing a lot of date work, you may want to look into JavaScript date libraries like Luxon, Day.js, 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);
}

And just in case this is not obvious, the reason we multiply minutes by 60000 is to convert minutes to milliseconds.

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:

const NOV = 10; //because JS months are off by one...
addMinutes(new Date(2014, NOV, 2), 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) {
  if(!(date instanceof Date))
    return undefined;
  var ret = new Date(date); //don't change original date
  var checkRollover = function() { if(ret.getDate() != date.getDate()) ret.setDate(0);};
  switch(String(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.

Kip
  • 107,154
  • 87
  • 232
  • 265
  • 19
    This is very powerful; It works for any amount of minutes even if number was negative. – Wahid Bitar Feb 24 '11 at 16:48
  • 5
    For seconds, multiply by 1000 instead of 60k. – ashes999 Apr 20 '15 at 02:33
  • 2
    The dateAdd() function is great! But there is one note from me - semantically, the **unit** should be "minute", "second", etc. and the **interval** should be the amount (2, 10, 45, ...), not vice versa. Otherwise the idea is good. – Vasil Popov Feb 20 '17 at 10:16
  • @VasilPopov I see your point, I was just following the terminology used by the MySQL function I'm familiar with. You can always rename however you wish when you copy paste. :) – Kip Feb 20 '17 at 19:36
  • True :) Anyway, as you also mentioned, it is much clear, nice and easy just using moment.js - `var time = moment('2017-02-11 09:00:00').add(30, 'm');` – Vasil Popov Feb 27 '17 at 12:27
  • Almost 600 upvotes for a poor answer??? The correct way to add to the time object is in its native value (milliseconds since midnight January 1st 1970) Thus `var timeIn30Min = new Date(new Date().valueOf() + 30 * 60 * 1000);` DO NOT USE the parsed output of Date for anything other than displaying time. – Blindman67 Mar 01 '17 at 03:57
  • @Blindman67 that's exactly what my answer says. Then it goes on to explain the unexpected issues you will encounter if you try to use that method to add days/weeks/months/years and presents an alternative. Nowhere is a date string parsed. – Kip Mar 01 '17 at 04:52
  • You have 600 upvotes and i will defer to the popular consensus. (BTW "parsed output" is what I said, you parse the native value with getDate, getMonth, & getYear (also getYear has depreciated https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getYear)) – Blindman67 Mar 01 '17 at 05:22
  • Sorry my bad I read getYear.. Dont know where I saw that. Sorry. – Blindman67 Mar 01 '17 at 05:23
  • 1
    This answer fails to accommodate month roll overs, so 31 Jan plus one month gives 2 or 3 Mar depending on whether it's a leap year or not. The *addMonths* and *addYears* functions in Jacobi's answer deal with that so for me, it's a better answer. – RobG Mar 01 '17 at 05:40
  • 1
    @RobG Good point. I've added a fix for this and further emphasized the "use a library if possible" point. – Kip Mar 02 '17 at 23:16
  • @Blindman67 I'm using milliseconds to add hours/minutes/seconds. But how else would you add days/months/years other than using getDate()/getMonth()/getFullYear()? A day/month/year does not represent a fixed number of milliseconds. – Kip Mar 04 '17 at 18:01
  • 1
    Thanks a lot for that Vanilla function. Such a simple function that'll save me so much time! cheers! – Mathieu Turcotte Apr 12 '17 at 14:52
  • This should be `var newDateObj = moment(oldDateObj).add(30, 'm').toDate();` ( .toDate() should added to get a date object otherwise its a moment object) – roneo Sep 13 '17 at 15:20
  • Is it bad practice to do it like this? `new Date(Date.now() + 86400000)` – Ari Feb 19 '19 at 03:01
  • 1
    @KeepMove that depends on what you need to do. 86400000 ms is equal to 24 hours, which is not *always* the same thing as 1 day (as I explain in the answer). So you need to decide if you are trying to add 24 hours, or add 1 day, and pick the solution that fulfills your needs. – Kip Feb 20 '19 at 05:11
  • Hey @Kip, this answer is giving me strange output... your naive function is erroneously outputting the right date for me. See [here](https://stackoverflow.com/questions/56615246/add-a-duration-to-a-repeating-events-start-time-so-that-its-end-is-always-the) if you will. – zelusp Jun 16 '19 at 00:51
  • 1
    @zelusp Thanks for pointing this out. I made an edit to this answer to improve readability but ended up introducing the bug you point out in your question. I've fixed this answer, and provided an answer in your new question as well. – Kip Jun 26 '19 at 15:25
  • Folks, take @Kip 's advice and just use a library! +1 for [moment.js](http://momentjs.com/)! It took less *time* to set up and use than figuring this out on my own. – Dave Jan 27 '20 at 22:36
  • Great advice to use a library. However, as of September 2020 Moment.js is considered legacy and **should no longer be used** in most cases. See [my answer](https://stackoverflow.com/a/66920049/4136777) for details. – Duncan Lukkenaer Apr 02 '21 at 13:30
  • https://date-fns.org/ is the best Date library in JS – Oleg Abrazhaev Mar 23 '23 at 17:26
360
var d1 = new Date (),
    d2 = new Date ( d1 );
d2.setMinutes ( d1.getMinutes() + 30 );
alert ( d2 );
GirkovArpa
  • 4,427
  • 4
  • 14
  • 43
Jamie
  • 5,994
  • 1
  • 18
  • 15
  • 158
    @Jamie: You don't need two `Date` objects. `var d = new Date(); d.setMinutes(d.getMinutes() + 30);` – Grant Wagner Jul 29 '09 at 21:28
  • 19
    @Grant: I assumed d2 = "I'd like to get a Date object" and d1 = "to another Date object" – Jamie Jul 30 '09 at 17:53
  • 7
    @CKeene, setMinutes & getMinutes are part of plain old Javascript (though datejs does provide a whole bunch of other stuff). – s29 Feb 15 '12 at 05:19
  • 7
    FYI- this can break across Daylight Saving Time boundaries. JSFiddle demos: ["spring forward"](http://jsfiddle.net/uj9462vp/6/) / ["fall back"](http://jsfiddle.net/5zLzsnsf/4/) (Thanks @Spig for this) – Kip Sep 17 '14 at 17:18
  • 3
    @trevorgrayson If a parameter you specify is outside of the expected range, setMinutes() attempts to update the date information accordingly. For example, if you use 100, the hours will be incremented by 1 and 40 will be used for minutes. – Mihai Crăiță Dec 30 '14 at 06:34
210

var oldDateObj = new Date();
var newDateObj = new Date();
newDateObj.setTime(oldDateObj.getTime() + (30 * 60 * 1000));
console.log(newDateObj);
hashed_name
  • 553
  • 6
  • 21
chaos
  • 122,029
  • 33
  • 303
  • 309
  • 4
    Note that `setTime` returns a numeric millisecond timestamp, not a date object. (Don’t think you can do a one-liner.) – Alan H. Dec 24 '11 at 00:33
  • 15
    `var in30Mins = new Date(+new Date() + 1.8e6)` is a one–liner, but not sure it's any better than a two–liner. ;-) – RobG Jun 18 '17 at 12:44
  • 2
    In case the winky face was too subtle, using `+new Date()` is not generally recommended: https://stackoverflow.com/a/221565 However, using the info from that link, I believe the following is fine: `new Date(Date.now() + (30 * 60 * 1000))` – DharmaTurtle May 10 '21 at 23:37
  • returning the date - new Date(newDateObj.setTime(oldDateObj.getTime() + (30 * 60 * 1000))); – Vineesh TP Jul 06 '22 at 07:00
134

var now = new Date();
now.setMinutes(now.getMinutes() + 30); // timestamp
now = new Date(now); // Date object
console.log(now);
hashed_name
  • 553
  • 6
  • 21
Teo Graca
  • 1,341
  • 1
  • 8
  • 2
68

Maybe something like this?

var d = new Date();
var v = new Date();
v.setMinutes(d.getMinutes()+30);

console.log(v)
hashed_name
  • 553
  • 6
  • 21
Tyler Carter
  • 60,743
  • 20
  • 130
  • 150
  • 7
    @Chacha102: You don't need two `Date` objects. `var d = new Date(); d.setMinutes(d.getMinutes() + 30);` – Grant Wagner Jul 29 '09 at 21:29
  • 15
    He wanted two date objects. Read the Question. One Date object which is 30 minutes ahead of another date object. – Tyler Carter Jul 29 '09 at 21:38
  • 5
    Does this work ok if it loops past the hour? So if I call it at 11:59, does it schedule ok at 12:29? – Chris Rae Sep 20 '17 at 23:18
  • 3
    @ChrisRae yes, it does. `If a parameter you specify is outside of the expected range, setMinutes() attempts to update the date information in the Date object accordingly.` – frido Mar 26 '19 at 14:19
63

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

These 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;
};
ashleedawg
  • 20,365
  • 9
  • 72
  • 105
Jacobi
  • 1,508
  • 15
  • 29
  • Can anyone see any issue with this approach? – The Dembinski Oct 24 '16 at 17:54
  • 1
    use moment.js instead – Victor Pudeyev Nov 05 '16 at 23:36
  • @TheDembinski—what issues are you expecting? Extending built-ins is generally disliked, but I can't see an issue with Date. It would be nice if each major increment would also optionally set its minor increments (as the *set\** methods do), so *addHours* optionally took minutes, seconds and milliseconds so you could do `date.addHours(3, 30)` to add 3 hours and 30 minutes. *addYears* would take years, months and days, *addMonths* would take months and days, *addMinutes* would take minutes, seconds, milliseconds, etc. – RobG Mar 01 '17 at 03:27
  • how can you add 4:45 mins with tihs – Transformer Dec 28 '17 at 04:04
  • 1
    Hi @transformer I would do something like this `new Date().addHours(4).addMinutes(45);` You can call as many as you want, because the methods return "this" which is the current Date Object. – Jacobi Dec 28 '17 at 17:05
  • thanks for the response @Jacobi in my case I dont know the hours before hand. For e.g. I am trying to total all the hours worked in a TableCol across the table rows, to show summary hours. While I can iterate the table; I still dont know how to dynamically, fragment the hours & mins. Here you have it as constants, _any chance to make it using a variable function_ – Transformer Dec 28 '17 at 20:51
  • 2
    Hi @transformer, I'm not sure I understood your problem, but these are prototype function, you can use in any order you want, ex: `var dt = new Date();` then `dt.addMinutes(45); dt.addHours(4);` or even `dt.addMinutes(285);` or also `dt.addMinutes(45).addHours(4);` all will work. If you have a question with some code example, for your problem post it here I'll be happy to help you. – Jacobi Dec 29 '17 at 14:26
47

One line code

  var afterSomeMinutes = new Date(new Date().getTime() + minutes * 60000);

where minutes is a number

Mansour Alnasser
  • 4,446
  • 5
  • 40
  • 51
30

Stop using Moment.js

As recommended by other great answers, in most cases it's best to use a library when dealing dates. However, it's important to know that as of September 2020 Moment.js is considered legacy and should no longer be used in new projects.

Quoting Moment's statement in their official docs:

We would like to discourage Moment from being used in new projects going forward. [...] We now generally consider Moment to be a legacy project in maintenance mode. It is not dead, but it is indeed done.

Modern libraries

Below are alternatives recommended by Moment.

Luxon

Luxon can be thought of as the evolution of Moment. It is authored by Isaac Cambron, a long-time contributor to Moment. Please read Why does Luxon exist? and the For Moment users pages in the Luxon documentation.

  • Locales: Intl provided
  • Time Zones: Intl provided
import {DateTime} from 'luxon'

function addMinutes(date, minutes) {
    return DateTime.fromJSDate(date).plus({minutes}).toJSDate()
}

Day.js

Day.js is designed to be a minimalist replacement for Moment.js, using a similar API. It is not a drop-in replacement, but if you are used to using Moment's API and want to get moving quickly, consider using Day.js.

  • Locales: Custom data files that can be individually imported
  • Time Zones: Intl provided, via a plugin
import dayjs from 'dayjs'

function addMinutes(date, minutes) {
    return dayjs(date).add(minutes, 'minutes').toDate()
}

date-fns

Date-fns offers a series of functions for manipulating JavaScript Date objects. For more details, scroll to "Why date-fns?" on the date-fns home page.

  • Locales: Custom data files that can be individually imported
  • Time Zones: Intl provided, via a separate companion library
import {addMinutes} from 'date-fns'

function addMinutesDemo(date, minutes) {
    return addMinutes(date, minutes)
}

js-Joda

js-Joda is a JavaScript port of Java's Three-Ten Backport, which is the base for JSR-310 implementation of the Java SE 8 java.time package. If you are familiar with java.time, Joda-Time, or Noda Time, you will find js-Joda comparable.

  • Locales: Custom data files via add-on module
  • Time Zones: Custom data files via add-on module
import {LocalDateTime, nativeJs, convert} from '@js-joda/core'

function addMinutes(date, minutes) {
    return convert(
        LocalDateTime.from(
            nativeJs(date)
        ).plusMinutes(minutes)
    ).toDate()
}
Duncan Lukkenaer
  • 12,050
  • 13
  • 64
  • 97
  • 1
    @Koslun Thanks for the feedback. I've added an example for each library. – Duncan Lukkenaer Apr 20 '21 at 18:46
  • Because a library is done doesn't mean you should stop using it. If its done, it will only mean that it is stable. Only more reason to use is instead of the libraries still in development with bugs. – Niels Lucas Oct 11 '21 at 13:29
  • @NielsLucas As mentioned by the Moment authors themselves, it is discouraged to use the package for new projects. You can still use it, but there are more better, more modern alternatives available. The fact that these are newer does not necessarily mean that they contain more bugs. – Duncan Lukkenaer Oct 12 '21 at 11:33
24

One-liner no utilities:

new Date(+new Date() + 60000*15) // +15 minutes
C B
  • 12,482
  • 5
  • 36
  • 48
20

The easiest way to solve is the to recognize that in javascript dates are just numbers. It starts 0 or 'Wed Dec 31 1969 18:00:00 GMT-0600 (CST). Every 1 represents a millisecond. You can add or subtract milliseconds by getting the value and instantiating a new date using that value. You can manage it pretty easy with that mind.

const minutesToAdjust = 10;
const millisecondsPerMinute = 60000;
const originalDate = new Date('11/20/2017 10:00 AM');
const modifiedDate1 = new Date(originalDate.valueOf() - (minutesToAdjust * millisecondsPerMinute));
const modifiedDate2 = new Date(originalDate.valueOf() + (minutesToAdjust * millisecondsPerMinute));

console.log(originalDate); // Mon Nov 20 2017 10:00:00 GMT-0600 (CST)
console.log(modifiedDate1); // Mon Nov 20 2017 09:50:00 GMT-0600 (CST)
console.log(modifiedDate2); // Mon Nov 20 2017 10:10:00 GMT-0600 (CST)
tsacodes
  • 350
  • 3
  • 8
13

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));
Jonathan
  • 894
  • 2
  • 9
  • 20
  • 3
    You could just do `return new Date(this.getTime() + minutes * 60000);`, I the interim *copiedDate* is not necessary. ;-) – RobG Mar 01 '17 at 03:31
12

You should get the value of the current date to get the date with (ms) and add (30 * 60 *1000) to it. Now you have (current date + 30 min) with ms

console.log('with ms', Date.now() + (30 * 60 * 1000))
console.log('new Date', new Date(Date.now() + (30 * 60 * 1000)))
9

it is simple as it is;

let initial_date = new Date;
let added30Min = new Date(initial_date.getTime() + (30*60*1000));
James
  • 23
  • 6
Cedrick Campoto
  • 121
  • 1
  • 3
7

Here is the ES6 version:

let getTimeAfter30Mins = () => {
  let timeAfter30Mins = new Date();
  timeAfter30Mins = new Date(timeAfter30Mins.setMinutes(timeAfter30Mins.getMinutes() + 30));
};

Call it like:

getTimeAfter30Mins();
Zameer Ansari
  • 28,977
  • 24
  • 140
  • 219
7

Here is my one-liner:

console.log('time: ', new Date(new Date().valueOf() + 60000))
Jason Mullings
  • 850
  • 14
  • 10
6

I feel many of the answers here are lacking a creative component, very much needed for time travel computations. I present my solution for a temporal translation of 30 minutes.

(jsfiddle here)

function fluxCapacitor(n) {
    var delta,sigma=0,beta="ge";
    (function(K,z){

        (function(a,b,c){
            beta=beta+"tT";
            switch(b.shift()) {
                case'3':return z('0',a,c,b.shift(),1);
                case'0':return z('3',a,c,b.pop());
                case'5':return z('2',a,c,b[0],1);
                case'1':return z('4',a,c,b.shift());
                case'2':return z('5',a,c,b.pop());
                case'4':return z('1',a,c,b.pop(),1);
            }
        })(K.pop(),K.pop().split(''),K.pop());
    })(n.toString().split(':'),function(b,a,c,b1,gamma){
       delta=[c,b+b1,a];sigma+=gamma?3600000:0; 
       beta=beta+"im";
    });
    beta=beta+"e";
    return new Date (sigma+(new Date( delta.join(':')))[beta]());
}
unsynchronized
  • 4,828
  • 2
  • 31
  • 43
6

You could do this:

let thirtyMinutes = 30 * 60 * 1000; // convert 30 minutes to milliseconds
let date1 = new Date();
let date2 = new Date(date1.getTime() + thirtyMinutes);
console.log(date1);
console.log(date2);
rayalois22
  • 161
  • 3
  • 7
6
let d = new Date();
d.setMinutes(d.getMinutes() + 30);

// console.log(d)
aljgom
  • 7,879
  • 3
  • 33
  • 28
  • Note: `setMinutes()` modifies the object but returns a timestamp, so `console.log(d.setMinutes(d.getMinutes() + 30))` would log a timestamp, and `console.log(d)` would log the Date object – aljgom Nov 12 '22 at 13:54
5

I know that the topic is way too old. But I am pretty sure that there are some developpers who still need this, so I made this simple script for you. I hope you enjoy it!

Hello back, It's 2020 and I've added some modification hope it will help a lot better now!

Hello again, It is 2022 and I came back again to fix some issues and give a better naming for the methods & functions.

function addTimeToDate(addedTime, date){
  let generatedTime = date.getTime();
  if(addedTime.seconds) generatedTime += 1000 * addedTime.seconds; //check for additional seconds 
  if(addedTime.minutes) generatedTime += 1000* 60 * addedTime.minutes;//check for additional minutes 
  if(addedTime.hours) generatedTime += 1000 * 60 * 60 * addedTime.hours;//check for additional hours 
  return new Date(generatedTime);
}

Date.prototype.addTime = function(addedTime){
  return addTimeToDate(addedTime, this);
}

let futureDate = new Date().addTime({
    hours: 16, //Adding one hour
    minutes: 45, //Adding fourty five minutes
    seconds: 0 //Adding 0 seconds return to not adding any second so  we can remove it.
});
<button onclick="console.log(futureDate)">Travel to the future</button>
Adnane Ar
  • 683
  • 7
  • 11
  • @AdnaneAr: sir can you tell me how to add minute to 8:00 AM this format of time? – Kapil Soni Aug 06 '20 at 09:59
  • @Kapilsoni *Date.prototype.toAmericanFormat = function(){ const halfDay = 12; let isAfternoon = false; if( this.getHours() > 12 ) { isAfternoon = true; } return `${!isAfternoon?this.getHours():this.getHours()-halfDay}:${this.getMinutes()}${isAfternoon?'PM':'AM'}`; }* – Adnane Ar Aug 06 '20 at 14:44
  • I don't know whether it's the right answer to your request but I have just written this simple function for you. It can be used just like : `new Date().strtotime({hours: 8, minutes: 25}).toAmericanFormat();` – Adnane Ar Aug 06 '20 at 14:47
5

Here is the IsoString version:

console.log(new Date(new Date().setMinutes(new Date().getMinutes() - (30))).toISOString());
gildniy
  • 3,528
  • 1
  • 33
  • 23
5
var add_minutes =  function (dt, minutes) {
return new Date(dt.getTime() + minutes*60000);
}
 console.log(add_minutes(new Date(2014,10,2), 30).toString());
ISK
  • 85
  • 1
  • 9
  • very useful, we can even send a date parsed from a string with Date.parse(string) and then format the result back to an appropriate string – msanjay Jan 12 '22 at 05:30
5

One way to 'add' 30 minutes is to create a second date object (mostly for demonstration) and set the minutes to minutes + 30. This will account for adjusting the hour as well if the first time is less than 30 minutes from the next hour. (i.e., 4:45 to 5:15)

const first = new Date();
console.log("first date :", first.toString());
const second = new Date(first);
const newMinutes = second.getMinutes() + 30;
console.log("new minutes:", newMinutes);
second.setMinutes(newMinutes);
console.log("second date:", second.toString());
phentnil
  • 2,195
  • 2
  • 14
  • 22
4

Use an existing library known to handle the quirks involved in dealing with time calculations. My current favorite is moment.js.

<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.js"></script>
<script>
 var now = moment(); // get "now"
 console.log(now.toDate()); // show original date
 var thirty = moment(now).add(30,"minutes"); // clone "now" object and add 30 minutes, taking into account weirdness like crossing DST boundries or leap-days, -minutes, -seconds.
 console.log(thirty.toDate()); // show new date
</script>
Ouroborus
  • 16,237
  • 4
  • 39
  • 62
  • 3
    Answers can't improve if you downvote without giving a reason. – Ouroborus Jul 26 '16 at 18:22
  • The OP asked for a JavaScript solution, not a framework/library. – mattpark22 Jul 27 '16 at 11:22
  • 2
    @mattpark22 While I understand what you're getting at, a javascript library is still javascript. I could rip out just the relevant pieces of the library and present those as a code solution. OP would have an answer that was javascript, in the sense that you mean it, but would be unaware of a (possibly) acceptable, general purpose solution. Also, adding 30 minutes is not nearly as trivial as most of the answers make it sound, as there are a lot of edge cases not handled by the Date object. For example, the most popular answer breaks when crossing DST boundaries. – Ouroborus Jul 27 '16 at 18:33
  • @Ouroborus—libraries should not be the only solution provided if the OP has not asked for a library in the OP or tags. Otherwise, answers can become just a litany of ways to do something in different libraries and the OP is left no wiser to their actual issue (which in this case is fairly trivial to solve). – RobG Mar 01 '17 at 05:36
  • 1
    @RobG No one's suggesting that only library solutions should be provided. OP can't specifically ask for a library as that would cause the question to be off-topic. Asking "How do I do it with JavaScript?" could be construed as specifying that this is specific to javascript (asking for a solution in a specific language as opposed to asking for a raw code solution) especially given that this detail is repeated in the title and the tags. – Ouroborus Mar 01 '17 at 17:08
4

Other solution:

var dateAv = new Date();
var endTime = new Date(dateAv.getFullYear(), dateAv.getMonth(), dateAv.getDate(), dateAv.getHours(), dateAv.getMinutes() + 30);
          
German Gracia
  • 351
  • 4
  • 8
3

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
Blaskovicz
  • 6,122
  • 7
  • 41
  • 50
2

Just another option, which I wrote:

DP_DateExtensions Library

It's overkill if this is all the date processing that you need, but it will do what you want.

Supports date/time formatting, date math (add/subtract date parts), date compare, date parsing, etc. It's liberally open sourced.

Jim Davis
  • 1,230
  • 6
  • 11
1

simply you can use this code with momnet library:

console.log(moment(moment()).add(30,"minutes").format('MM/DD/YYYY hh:mm:ss'));
DolDurma
  • 15,753
  • 51
  • 198
  • 377
1
var myDate= new Date();
var MyNewDate = new Date 
(myDate.getFullYear(),myDate.getMonth(),myDate.getDate(),myDate.getMinutes()+10,01,01)
ISK
  • 85
  • 1
  • 9
1
const MINUTE = 60 * 1000;
new Date(Date.parse(yourDate) + numOfMins * MINUTE)
Sahil Jaidka
  • 271
  • 1
  • 5
  • 13