0

Hello I have a function which converts a local time to UTC using the local timezone and date:

this.conversion.dateTimeToTime('2022-07-04 12:30', 'America/Los_Angeles');

public dateTimeToTime(date, timezone = 'UTC') {
    date = new Date(date);
    return date.toLocaleTimeString('en-GB', {timeZone: timezone, hour12: false});
  }
}

this is 12:30 local to UTC which should be 20:30(ish) but the output is 4:30utc instead going backwards

I am wondering what I am doing wrong

Thanks

  • `new Date('2022-07-04 12:30')` depends on your local time zone. You need to make your input data not dependant on that. I'm not an expert in the (utterly complicated) string parsing logic of JavaScript date functions but `new Date('2022-07-04T12:30:00Z')` seems to use UTC (at least in Firefox) and there's maybe a more reliable way. – Álvaro González Jul 06 '22 at 13:49
  • @ÁlvaroGonzález– `new Date('2022-07-04 12:30')` returns an invalid date in Safari. It is strongly recommended to not use the built–in parser for unsupported formats as the result is implementation dependent. – RobG Jul 08 '22 at 11:40

2 Answers2

1

Keeping date as simple date string(2022-01-31) causes data loss in JS and providing it to Date constructor can result in wrong date. Check this SO question for more.

Generally I convert my date to ISO format by using Date.toISOString. Next when I want to parse it as JS Date object, I use parseISO method of date-fns.

Here is a CodeSandbox example: https://codesandbox.io/s/summer-bush-iv0h2g?file=/src/index.js

im_tsm
  • 1,965
  • 17
  • 29
  • ECMAScript implementations have been required to correctly parse the output of *toISOString* since ECMAScript 2011 (ed 5), so using *parseISO* for that is not necessary. – RobG Jul 08 '22 at 11:45
0

I have used moment-tz instead:

import * as moment from "moment-timezone";

let blah = moment.tz("2019-06-03 12:30", "America/Los_Angeles");

console.log(blah.format());
console.log(blah.clone().tz("UTC").format());