0

when i create a new Date Object from a string i get a wrong date by one day and I dont understand why. I've already verified, that it does not come from timezone difference.

var myDate new Date("2016-04-12T22:04:00.000Z")
console.log(myDate);
Wed Apr 13 2016 00:04:00 GMT+0200 (Central European Summertime)
juleee
  • 456
  • 1
  • 7
  • 20
  • 4
    Because it's converting it to local time from UTC, as it states it's +2 so you roll into next day as it's 10:04pm. – Lloyd Apr 13 '16 at 19:02
  • is there a way to keep it in UTC? – juleee Apr 13 '16 at 19:03
  • 2
    *"I've already verified, that it does not come from timezone difference."* - How did you do that? – nnnnnn Apr 13 '16 at 19:03
  • @juleee - it's not a matter of "keep"ing it UTC. The date object is the date object and represents a certain time...you can output that time as a local representation or UTC. `.toString()` (what happens when you coerce it to a string directly like you're doing) outputs it as a string representing local time. It sounds like you need to spend some time learning about dates in general: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date – Jimbo Jonny Apr 13 '16 at 19:11

2 Answers2

0

The issue is timezones. 22:04:00 in UTC is 00:04:00 in UTC+2.

To get the UTC time, fetch the date parts with myDate.getUTCHours(), mydate.getUTCMinutes(), etc. See a full list of Date methods.

Scimonster
  • 32,893
  • 9
  • 77
  • 89
-1

You can get the UTC string of your date-

var myDate=new Date("2016-04-12T22:04:00.000Z");

myDate.toUTCString()
/* returne value:
Tue, 12 Apr 2016 22: 04: 00 GMT
*/
kennebec
  • 102,654
  • 32
  • 106
  • 127
  • Hi @kennebec, excuse me to use this question as a place to communicate with you. But I was using your awesome `sharedStart` function but needed help with a modification. If you are available may you please help me - I posted the question here - https://stackoverflow.com/q/49134350/1828637 – Noitidart Mar 06 '18 at 15:41