0

I'm newbie in JS and while learning the Date object I got stucked on this issue that I can't understand.

let myDate= new Date("2012/07/1")
console.log(myDate) //the output is "2012-06-30T22:00:00.000Z"

so why did the date change, and the time is set automatically to 22? anyone can clarify that for me?

Isam
  • 1
  • 1

1 Answers1

1

It didn't change. But you initialized it with a time based on your local timezone (UTC+2 apparently) and then you saw the same time in UTC.

2012-06-30 22:00:00 UTC+0 is the same time as 2012-07-01 00:00:00 UTC+2 (or 2012-07-01 02:30:00 UTC-2:30 which is the current timezone in Newfoundland in the summer, for that matter - just saying).

(Side note: If you want to understand how complex timezones really are, take a look at this video. It's both entertaining and educational!)

Maybe this will make it a bit clearer:

const d = new Date('2012/07/1') // note: this is local time! and not
                                // a good way in the first place, because
                                // it is not guaranteed to work, and it
                                // may very well vary between environments.

console.log(d.valueOf()) // 1341093600000 - timestamp value
console.log(d.toISOString()) // 2012-06-30T22:00:00.000Z - google ISO8601

console.log(d.toUTCString()) // Sat, 30 Jun 2012 22:00:00 GMT
console.log(d.toString()) // Sun Jul 01 2012 00:00:00 GMT+0200 (Mitteleuropäische Sommerzeit)
console.log(d.toLocaleString()) // 1.7.2012, 00:00:00 - this is my local format

console.log(d.getUTCFullYear()) // 2012
console.log(d.getUTCMonth()) // 5 - note that JS uses months starting with 0!
console.log(d.getUTCDate()) // 30
console.log(d.getUTCHours()) // 22
console.log(d.getUTCMinutes()) // 0

console.log(d.getFullYear()) // 2012
console.log(d.getMonth()) // 6 - note that JS uses months starting with 0!
console.log(d.getDate()) // 1
console.log(d.getHours()) // 0
console.log(d.getMinutes()) // 0

You can see all this also in the documentation for Date.

As Matt Johnson-Pint pointed out in the comments: This isn't a reliable way to initialize a date object anyway, take a look at the docs for the Date constructor for other options, for example new Date(2012, 6, 1).

CherryDT
  • 25,571
  • 5
  • 49
  • 74
  • 2
    Also worth mentioning - passing a string format like `2012/07/1` *might* work, but it's implementation specific, and results will vary on environment, browser, locale settings, etc. [The ECMAScript spec](https://www.ecma-international.org/ecma-262/11.0/index.html#sec-date.parse) allows such formats only under the phrasing `"... the function may fall back to any implementation-specific heuristics or implementation-specific date formats."` – Matt Johnson-Pint Jul 13 '20 at 20:33