convert pacific time to gmt in javascript

To convert Pacific Time (PT) to Greenwich Mean Time (GMT) in javascript, we can use the toLocaleString() method and pass in the timeZone and timeZoneName options. Here's an example:

index.tsx
// create a date object for Pacific Time
let ptDate = new Date();
ptDate.toLocaleString("en-US", {timeZone: "America/Los_Angeles"});

// get the GMT time by setting the timezone to UTC
let gmtDate = new Date(ptDate.toLocaleString("en-US", {timeZone: "America/Los_Angeles", timeZoneName: "short"}));
gmtDate.setMinutes(ptDate.getMinutes() + ptDate.getTimezoneOffset());
gmtDate.toLocaleString("en-US", {timeZone: "UTC", timeZoneName: "short"});
444 chars
9 lines

In the example above, we create a Date() object for the current time in Pacific Time. We then use toLocaleString() to get the date string in Pacific Time format, and set the timeZone option to "America/Los_Angeles" to indicate that this is a PT date.

To convert this to GMT, we create a new Date() object and set the timezone to UTC ("UTC"). We also set the timezone offset of the new date to the offset of the PT date. Finally, we use toLocaleString() again with the timeZone and timeZoneName options to get the date string in GMT format.

Note that the timeZone option requires a valid timezone name from the IANA Time Zone database. You can find a list of valid timezone names here: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones

gistlibby LogSnag