Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add days to a date without changing GMT time

I am working on an application where all dates used are round GMT dates, e.g. 2015-10-29T00:00:00.000Z.

I am using following function to add days to a date :

function addDays(date, days) {
  var result = new Date(date);
  result.setDate(result.getDate() + days);
  return result;
}

But, I just realized it doesn't work when crossing daylight saving time changing day :

var myDate = new Date('2015-10-24T00:00:00.000Z');
for(i = 0; i<4; i++) {
  console.log(JSON.stringify(myDate));
  myDate = addDays(myDate, 1);
}

Outputs this :

"2015-10-24T00:00:00.000Z"
"2015-10-25T00:00:00.000Z"
"2015-10-26T01:00:00.000Z"
             ^
"2015-10-27T01:00:00.000Z"
             ^

Note that the two last dates are not round anymore.

What is the proper way to deal with this ?

like image 980
yannick1976 Avatar asked Oct 28 '15 13:10

yannick1976


People also ask

How do you add days to a new date?

To add days to a date in JavaScript: Use the getDate() method to get the day of the month for the given date. Use the setDate() method, passing it the result of calling getDate() plus the number of days you want to add. The setDate() method will add the specified number of days to the Date object.

How can I get the current date and time in GMT in JavaScript?

Use the toUTCString() method to get the GMT representation of a date, e.g. new Date(). toUTCString() . The method converts the date to a string, using the UTC time zone, which shares the same current time with GMT. Copied!


1 Answers

Edit: Actually I found a solution that is definitely better. I'm leaving this for the sake of exhaustivity.

The problem is that Date.setDate() adds a day without changing the local time. But this means the GMT time does change !

Adding a day without changing the GMT time is actually as simple as adding 24 * 3600 * 1000 milliseconds to the date's time :

function addGMTDays(date, days) {
  var result = new Date(date);
  result.setTime(result.getTime() + days * 24 * 3600 * 1000);
  return result;
}

Then :

var myDate = new Date('2015-10-24T00:00:00.000Z');
for(i = 0; i<4; i++) {
  console.log(JSON.stringify(myDate));
  myDate = addGMTDays(myDate, 1);
}

Outputs this :

"2015-10-24T00:00:00.000Z"
"2015-10-25T00:00:00.000Z"
"2015-10-26T00:00:00.000Z"
"2015-10-27T00:00:00.000Z"
like image 60
yannick1976 Avatar answered Sep 17 '22 08:09

yannick1976