How to add 30 minutes to a JavaScript Date object?
I'd like to get a Date object which is 30 minutes later than another Date object. How do I do it with JavaScript?
Solution :
If you are doing a lot of date work, you may want to look into JavaScript date libraries like Datejs or Moment.js
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);
}
A word of caution
Do not use the above to try add days. For example:
addMinutes(myDate, 60*24); //DO NOT DO THIS
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!
Instead, here is a more generic version of this function that I wrote. The syntax is modeled after MySQL DATE_ADD function.
function dateAdd(date, interval, units) {
var ret = new Date(date); //don't change original date
switch(interval.toLowerCase()) {
case 'year' : ret.setFullYear(ret.getFullYear() + units); break;
case 'quarter': ret.setMonth(ret.getMonth() + 3*units); break;
case 'month' : ret.setMonth(ret.getMonth() + units); 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;
}
http://stackoverflow.com/questions/1197928/how-to-add-30-minutes-to-a-javascript-date-object/1214753#1214753
COMMENTS