2

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

user3808307
  • 735
  • 3
  • 18
  • 45
  • 1
    Months are zero indexed so 5 is June. That's a strange format but you can get it by `new Date().toISOString().replace(/[^\d\.]/g,'').replace(/(^\d{8})/,'$1-')`, see [*How to format a JavaScript date*](https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date?r=SearchResults&s=1|1450.4192). – RobG Jun 04 '20 at 03:38
  • @RobG I think I am going to use this – user3808307 Jun 04 '20 at 03:48

4 Answers4

2

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)

Sven.hig
  • 4,315
  • 2
  • 5
  • 18
1

Month index starts from 0 with range 0-11 for 12 months - Month in JavaScript

Also check for Java Explaination - Month in Java

Vikas Dubey
  • 87
  • 1
  • 11
1

This is what you need!

var timeRef = new Date()

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

console.log(timeRef.getUTCMonth()+1) // returns 6
Always Helping
  • 13,486
  • 4
  • 8
  • 26
0

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>
Peter
  • 73
  • 2
  • 7
  • Hi @Peter thanks, yes it is, I just thing moment is a little too much for just this small thing, I was about to look into date-fns – user3808307 Jun 04 '20 at 03:47