convert gmt to pacific time in typescript

To convert a date string from GMT to Pacific time in TypeScript, you can use Moment.js and the Moment-Timezone library.

First, install Moment.js and Moment-Timezone:

npm install moment moment-timezone
35 chars
2 lines

Then, import Moment.js and Moment-Timezone in your TypeScript file:

index.ts
import * as moment from 'moment';
import 'moment-timezone';
60 chars
3 lines

Next, create a Moment.js object from your GMT date string and set its timezone to Pacific time:

index.ts
const gmtDateString = '2021-09-23T12:34:56Z';
const pacificTimezone = 'America/Los_Angeles';

const gmtMoment = moment(gmtDateString);
const pacificMoment = gmtMoment.tz(pacificTimezone);
188 chars
6 lines

You can then get the converted date string in the desired format:

index.ts
const format = 'YYYY-MM-DD HH:mm:ss';
const pacificDateString = pacificMoment.format(format);
console.log(pacificDateString); // outputs "2021-09-23 05:34:56"
159 chars
4 lines

Note that Moment.js and Moment-Timezone use the IANA Time Zone database, which is updated periodically. Make sure to keep your dependencies up to date to ensure accurate timezone conversions.

gistlibby LogSnag