I'm not used to work with dates in Javascript. I am trying to understand how it work, and in order to do that, I try to convert a string to timestamp, and then back to string.
So the first step is getting the timestamp:
const dateTime = new Date('2012-06-08').getTime()
console.log(dateTime) //1339113600000
Then, I am using this timestamp to generate a new date
const d = new Date(dateTime)
console.log(d) //Fri Jun 08 2012 02:00:00 GMT+0200 (W. Europe Daylight Time)
Everything looks good until there. Now I want to separate the date components (year, month, day)
console.log(d.getFullYear()) //2012
console.log(d.getMonth()) //5
console.log(d.getDay()) //5
The date is correct, but the month and the days are wrong. I don't get why it's returning 5th of May instead of 8th of June.
Does anyone has the answer to that?
Thanks!
答案 0 :(得分:0)
The getDay() method returns the day of the week. You want getDate, which returns the day of the month.
Months start at 0: 0 is January, 5 is June.
答案 1 :(得分:0)
Javascript is returning everything correctly, it returns 5 as a month because of the way it indexes months (0: January, 1: February, 2: March...), thus June will have index of 5.
Now about the day, what you actually want is the date, what you're asking for is the day of the week, so use getDate() instead.