0
votes

I have this line in my code:

var now= Utilities.formatDate(new Date(), SpreadsheetApp.getActive().getSpreadsheetTimeZone(), "EEE MMM d yyyy HH:mm:ss");

But I got error when I tried to get the year from now.

var yearnow= now.getFullYear();

The error is: "TypeError: Cannot find function getFullYear in object Wed Apr 5 2017 09:56:26"

Is there any way to fix this ?

Thank you in advance!!

1

1 Answers

1
votes

Utilities.formatDate returns a string. It does not return a date object like new Date() of javascript, hence you are getting that error.

You can do something like this to get your year and retain your format in now string

var now= Utilities.formatDate(new Date(), SpreadsheetApp.getActive().getSpreadsheetTimeZone(), "EEE MMM d yyyy HH:mm:ss");
var dt = new Date(now)  // This not the same as new Date()
var year = dt.getFullYear()

Hope that helps!

Edit

Using the below function:

function getDate(){
 var now= Utilities.formatDate(new Date(), SpreadsheetApp.getActive().getSpreadsheetTimeZone(), "EEE MMM d yyyy HH:mm:ss");
 var dt = new Date(now)
 Logger.log(now)
 Logger.log(dt.getFullYear())
 Logger.log(dt.getDate())
 Logger.log(dt.getMonth() + 1) //add 1 to compensate for the month index starting at 0, i.e Jan = 0, Feb =1, March = 2.... Dec = 11
}

I get this log

[17-04-04 20:35:03:355 CDT] Tue Apr 4 2017 20:35:03
[17-04-04 20:35:03:355 CDT] 2017.0
[17-04-04 20:35:03:356 CDT] 4.0
[17-04-04 20:35:03:356 CDT] 4.0

Which as you can see retains the date, year and month from as in the now string set in the first line of the code.