5

I can't figure out how to add one day to a date in Google App Script. I have this script:

function dateTest() {

var testDate = new Date();
var secondDate = new Date(testDate.getDate()+1);

 Logger.log(testDate);
 Logger.log(secondDate);
}

Which produces the following log:

[16-11-30 16:35:02:499 GMT] Wed Nov 30 16:35:02 GMT+00:00 2016

[16-11-30 16:35:02:500 GMT] Thu Jan 01 01:00:00 GMT+01:00 1970

I don't understand why it's not adding to the date?

Rubén
  • 34,714
  • 9
  • 70
  • 166
Dan Howard
  • 176
  • 2
  • 6
  • 16

3 Answers3

15

Change it to:

var testDate = new Date();
var secondDate = new Date();
secondDate.setDate(testDate.getDate()+1);

This should keep the day good for daylight savings time changes and leap year as well.

Karl_S
  • 3,364
  • 2
  • 19
  • 33
  • Thanks, I like the simplicity of this answer – Dan Howard Dec 01 '16 at 11:12
  • 4
    There is a potential gotcha here to keep in mind, depending what you're using this for. `getDate` gets the day of the month, i.e. today is "14", not Feb 14, 2020. If you're using this to compare dates you could have an issue. For example, if you want to know, is today's date greater than X date? Both 2/1/2020 and 4/1/2020 would return true because 14 > 1. – koanima Feb 14 '20 at 16:18
10

getDate() gets the day of the month. If you are passing a number to the Date constructor in new Date(value), it expects that number to be the number of milliseconds since the Unix epoch, see Date on MDN. So you're adding 31ms (today) to the unix epoch, hence the date is 01 Jan 1970 and a little bit.

To add one day try:

var secondDate = new Date(testDate.getTime() + 24 * 60 * 60 * 1000);

This adds the milliseconds in one day to testDate and creates a new Date from it.

getTime() gets the representation of a date in milliseconds since the Unix epoch, so by adding the number of ms in one day to it, you can create a new Date that is +1 day.

Bardy
  • 2,100
  • 1
  • 13
  • 11
  • Great, thanks for the explanation. I prefer the second answer for it's simplicity though. Appreciate your time. – Dan Howard Dec 01 '16 at 11:17
  • Not a good approach as in places where daylight saving is observed, days are not always 24 hours long. – RobG Jan 21 '20 at 21:56
5

You could also say:

var tomorrow = new Date(Date.now() + 1000*60*60*24)
Amit Agarwal
  • 10,910
  • 1
  • 32
  • 43