Creating a function that returns a date in Google Sheets

独自空忆成欢 提交于 2020-05-09 06:24:05

问题


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"


来源:https://stackoverflow.com/questions/60934973/creating-a-function-that-returns-a-date-in-google-sheets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!