Home > Back-end >  JS - Converting time from local to UTC using timezone's not converting properly
JS - Converting time from local to UTC using timezone's not converting properly

Time:07-07

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

CodePudding user response:

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

CodePudding user response:

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());

  • Related