new Date(2022, 4, 18, 16, 50);
why does this return the time reduced by three hours?
i get this "2022-05-18T13:50:00.000Z" instead of this "2022-05-18T16:50:00.000Z"
CodePudding user response:
why does this return the time reduced by three hours?
It doesn't, it gives you exactly the time you asked for — in your local time. But then you're getting a string from it in a way that gives you a string in UTC, not local time (the Z
at the end tells you it's UTC). Apparently there's a three-hour difference as of that date/time between your local timezone and UTC.
If you want to work in local time, use toLocaleString
to get a string formatted according to your current locale and using your timezone. If you want a string like the one you got, but in your local timezone, as far as I know you have to build it yourself.
If you want to work in UTC, build the date using the UTC
function: new Date(Date.UTC(2022, 4, 18, 16, 50));
CodePudding user response:
it's because of your timezone! for example:
let d = new Date(2022, 4, 18, 16, 50);
d.toLocaleString('en-US', { timeZone: 'America/New_York' });
CodePudding user response:
When you call the Date()
constructor with individual components it will interpret those in your local time. See point 5
on this MDN documentation page.
But when you print int without toLocaleString()
it will return the UTC time instead. Depending on your time zone this is more or less far away from what you have entered.