Converting timezones in javascript resulted in very strange results, am I doing something wrong or is it a bug?

流过昼夜 提交于 2021-02-11 12:33:34

问题


After isolating the problem in my current project .... I think something is not working currently with the Date object in javascript.

But I don't want to be arrogant because maybe I am doing something wrong, is it a bug? or am I doning something wrong?


I want to convert a date to diffrent time zone in javascript, I made this function:

function ConvertToTimeZone(date, timezone) {
   let convertedTimeString = date.toLocaleString("en-US", {hour12: false, timeZone: timezone})
   return new Date(convertedTimeString)
}

Then I am using it like this:

let testDate = new Date("Thu May 21 2020 17:04:05 GMT-0700 (Pacific Daylight Time)");
let convertedDate = ConvertToTimeZone(testDate, "Europe/London");

Or like this:

let testDate = new Date("Thu May 21 2020 18:04:05 GMT-0700 (Pacific Daylight Time)");
let convertedDate = ConvertToTimeZone(testDate, "UTC");

But something wrong is happening when I use this date:

let testDate = new Date("Thu May 21 2020 17:04:05 GMT-0700 (Pacific Daylight Time)");
let convertedDate = ConvertToTimeZone(testDate, "UTC");

with that last exmaple convertedDate end up with Invalid Date {}

And when I look closely in my ConvertToTimeZone the result of date.toLocaleString(...) is 5/22/2020, 24:04:05 which looks strange because the hours of that time cannot be 24 (it should be 0)

来源:https://stackoverflow.com/questions/61901653/converting-timezones-in-javascript-resulted-in-very-strange-results-am-i-doing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!