convert gmt to pacific time in javascript

To convert GMT (or any UTC time) to Pacific time in JavaScript, you can use Moment.js library which provides a lot of utilities to parse, validate, manipulate and display dates and times in JavaScript.

Here's an example code snippet that demonstrates the conversion of UTC to Pacific time using Moment.js library:

index.tsx
// Assuming input is in UTC format
const inputDate = '2021-02-05T23:20:00Z';

// Convert UTC to Pacific Time (PDT or PST depending on the date)
const pacificDate = moment.utc(inputDate).tz('America/Los_Angeles').format();
console.log(pacificDate);
248 chars
7 lines

In the above code:

  • We first define the input date string in UTC format (with Z at the end to indicate the timezone).
  • We then use the moment.utc() function to create a new Moment object from the input date string, and set it to UTC timezone.
  • Finally, we use the tz() function to convert the UTC time to Pacific Time zone (using America/Los_Angeles timezone identifier), and then use the format() function to get the string representation of the converted date and time.

Note that the format() function can take a format string argument to customize the output format of the date and time. Also, make sure to include the Moment.js library in your project before using the above code.

gistlibby LogSnag