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
Please help how to convert UTC Time Format to PST Time Format
Thanks
2
Answers
new Date(dateString);
is not UTC, but your local time.You need to use
Date.UTC(2023, 11, 18, 8, 0, 0, 0)
instead. AndtoLocaleString
does not require any conversions of time.Please see Date.UTC
You’re assuming
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)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