convert eastern time to pacific time in typescript

To convert Eastern Time to Pacific Time in TypeScript, we can use the moment-timezone library which provides a simple and intuitive way to work with time zones.

First, we need to install the moment-timezone library using npm:

npm install moment-timezone
28 chars
2 lines

Then, we can use the tz function from moment-timezone and the utcOffset function to convert Eastern Time to Pacific Time.

Here's how you can do it:

index.ts
import * as moment from 'moment-timezone';

// Set the input date and time in Eastern Time
const inputDateTime = moment.tz('2022-01-01 12:00:00', 'America/New_York');

// Convert Eastern Time to Pacific Time
const outputDateTime = inputDateTime.clone().utcOffset('-08:00').tz('America/Los_Angeles');

console.log(outputDateTime.format('YYYY-MM-DD HH:mm:ss z')); // "2022-01-01 09:00:00 PST"
391 chars
10 lines

In the above example, we first set the input date and time in Eastern Time. Then, we clone the input date and time and use the utcOffset function to set the UTC offset to -08:00 which represents Pacific Time. Finally, we use the tz function to set the time zone to America/Los_Angeles which is the time zone for Pacific Time.

The outputDateTime variable now contains the converted date and time in Pacific Time. We can format the output using the format function.

Note that we use clone when working with moment objects to avoid modifying the input date and time.

gistlibby LogSnag