1

How to convert a datetime to another timezone datetime then to utc using moment.js? This has to be done without using the timezone library so functions like tz and setTimezone are not available. The datetime is entered by the user.

So '5/24/2019 20:35' in Hawaii time is expected to be 5/25/2019 06:35AM in utc. My local computer is Pacific.

I tried this:

moment.utc(moment('5/24/2019 20:35','M/D/YYYY h:mm').utcOffset(-10).format("MM/DD/YYYY HH:mm:ss")).format('MM/DD/YYYY HH:mm:ss');

but it's not correct.

Tony_Henrich
  • 42,411
  • 75
  • 239
  • 374
  • If the time is "20:35" then the parse tokens should be "H:mm" (or perhaps HH:mm), not "h:mm". – RobG May 25 '19 at 07:07
  • 1
    Typically you just add or subtract the required difference in the timezones, however that also requires you to apply daylight saving adjustments manually. Using a timezone–aware library is a better solution, there are a few around. Consider [*Luxon*](https://moment.github.io/luxon/). – RobG May 25 '19 at 07:11
  • HH:mm and variations of it is not the issue. It parses fine. I am very aware of the timezone library as I mentioned, so no I can't use it for reasons I can't explain now other that it requires a lot of red tape in approvals, testing and such. Just go with the fact that I can't use it. I need a solution now. – Tony_Henrich May 25 '19 at 14:36

1 Answers1

1

Why do you need to convert to another timezone before converting to UTC?

Just do new Date("5/24/2019 20:35 -10").toUTCString() in pure JS.

On latest chrome it gives me the correct output "Sat, 25 May 2019 06:35:00 GMT"

If you need ISO format, do new Date(datestring).toISOString() //"2019-05-25T06:35:00.000Z"

suv
  • 1,373
  • 1
  • 10
  • 18
  • "*Just do…*" and expect an invalid date or unexpected results in certain hosts. Parsing non–standard strings with the built–in parser is a sure way to cause difficult to find bugs. See [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG May 26 '19 at 05:20