Month not correct when geting UTC month

Viewed 150

I am following these instructions https://stackoverflow.com/a/15012173/3808307

but I really don't get it. Now it is June 4th in my time zone and in UTC

I am doing timeRef.current = new Date()

Then

console.log(timeRef.current.getUTCFullYear()) // returns 2020
console.log(timeRef.current.getUTCMonth()) // returns 5

Why is my month 5? How can I get YYYYMMDD-HHMMSS.milliseconds in UTC univocally?

I don't want to have errors when, for example, it's Feb 29th, like here Javascript date - setting UTC month

I need a precise way of converting

Thank you

4 Answers

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)

This is what you need!

var timeRef = new Date()

console.log(timeRef.getUTCFullYear()) // returns 2020

console.log(timeRef.getUTCMonth()+1) // returns 6

If the use of an external library is possible for you, then I would suggest moment.js, like here:

alert("It's the " + moment.utc().format('MM') + ". month of the year " + moment.utc().format('YYYY') + ".") 
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script>

Related