Creating a function that returns a date in Google

2020-04-12 10:47发布

问题:

I created a function that takes in a date and number of months to add to that date and returns the next date. The function seems to be working perfectly, which I check using DEBUG. The strange thing is when I logger in the returned date using the line below,

monthstoadd = 18

date1.setFullYear(2019, 6, 1); 

returnDate = AddMonths(date1, monthstoadd);   // my selfmade function

Logger.log("returnDate(1):", returnDate.getMonth(), "/" , returnDate.getDay(), "/", returnDate.getFullYear());

the date in the log does not match the date in the debugger. Has anyone seen this? Also, does anyone know how to get the integer value of a number? I tried round but got some strange results.

For instance: Debugger show value as Tue Dec 01 2020 00:00:00 GMT-0500 (Eastern Standard Time) but log shows value as returnDate(1): 11.0 / 2.0 / 2020.0

回答1:

Issue:

getMonth returns the month from 0-11, where 0 represents January and 11 represents December. getDay returns Day of the week 0-6, where 0 represents Sunday and 6 represents Saturday. So, the log:

returnDate(1): 11.0 / 2.0 / 2020.0

is correct and represents

returnDate(1): Dec / Tue / 2020.0

Tue Dec 01 2020 00:00:00 GMT-0500 (Eastern Standard Time) 

Solution:

Use Intl:

console.info(new Intl.DateTimeFormat().format(returnDate))

or

console.log("returnDate(1):", returnDate.getMonth()+1, "/" , returnDate.getDate(), "/", returnDate.getFullYear());//Note Date vs Day and "+1"