Search code examples
javascriptreactjsdatetimedateformatter

How to Convert UTC time to PST time in react js


i am using react js and i am trying to convert UTC time to PST time but it is not converting according to online compilers.

Code:

const dateString = "12/18/2023, 8:00:00";
const utcDate = new Date(dateString);
const utcMilliseconds = utcDate.getTime();
const pstMilliseconds = utcMilliseconds - 8 * 60 * 60 * 1000;
const pstDate = new Date(pstMilliseconds);
const formattedPST = pstDate.toLocaleString("en-US", {
  timeZone: "America/Los_Angeles", // Set the time zone to PST
  hour12: true,
  year: "numeric",
  month: "numeric",
  day: "numeric",
  hour: "numeric",
  minute: "numeric",
  second: "numeric",
});

console.log(formattedPST);

OUTPUT:

12/17/2023, 10:30:00 AM

but this is the expected PST Converted time

enter image description here

Please help how to convert UTC Time Format to PST Time Format

Thanks


Solution

  • You're assuming

    const dateString = "12/18/2023, 8:00:00";
    const utcDate = new Date(dateString);
    

    will give you 8AM on the 18th Dec 2023 UTC

    It doesn't

    it gives you 8AM on the 18th Dec 2023 in YOUR timezone

    the code below should work properly - up to you to convert the string you have to a ISO date string to use in new Date (easy string manipulation though)

    const dateString = "2023-12-18T08:00:00Z";
    const utcDate = new Date(dateString);
    const formattedPST = utcDate.toLocaleString("en-US", {
      timeZone: "America/Los_Angeles", // Set the time zone to PST
      hour12: true,
      year: "numeric",
      month: "numeric",
      day: "numeric",
      hour: "numeric",
      minute: "numeric",
      second: "numeric",
    });
    
    console.log(formattedPST);

    Note: you don't need to add/subtract any hours/minutes from the date, because the date will now be correct, you just need to display the date in your chosen timezone, and .toLocaleString will do the heavy lifting for you