0

I'm confused about how this time conversion works. I have timestamp 1462060800000 which when I turn in to date correctly becomes: Sun May 01 2016 02:00:00 GMT+0200 (Central European Summer Time)

but then when I want to get the month with const startMonth = start.getUTCMonth() I get 4 instead of 5. Why is this happening and what do I need to do to get the correct month?

const timestamp = 1462060800000
const start = new Date(timestamp)
console.log(start) // Sun May 01 2016 02:00:00 GMT+0200 (Central European Summer Time)

const startYear = start.getUTCFullYear()
const startMonth = start.getUTCMonth()
console.log(startMonth) // 4

2

4 Answers 4

0

getUTCMonth() returns zero-based months. 4 is correct. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCMonth.

1
  • Yes, I just realized that. Thanks Commented Nov 30, 2020 at 18:00
0

I get it it's actually a month index that starts with 0.

0

The getUTCMonth() returns the month of the specified date according to universal time, as a zero-based value (where zero indicates the first month of the year).

From the docs see Date.prototype.getUTCMonth()

0

The getUTCMonth() method, like getMonth(), has a zero (0) count. This means that the period will be like this - 0 and 11. To get the desired month, you need to add +1:

const startMonth = start.getUTCMonth() + 1;

Loot it.

const timestamp = 1462060800000;
const start = new Date(timestamp);
console.log(start); // Sun May 01 2016 02:00:00 GMT+0200 (Central European Summer Time)

const startYear = start.getUTCFullYear();
const startMonth = start.getUTCMonth() + 1;
console.log(startMonth);

Not the answer you're looking for? Browse other questions tagged or ask your own question.