1

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 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you!! But in this case, I can't keep my time zone. It takes the default time zone. How can I get the day, month and year in my time zone?
I am kind of lost! The new date object is created using the var now, so it will retain the day, month and year of string now. Not sure how it defaults to default time zone!
That is right!! Thank you a lot. I used the getDay() function that is why I couldn't get the right day.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.