convert pacific time to eastern time in typescript

To convert Pacific time to Eastern time in Typescript, you can use either the moment.js or date-fns library. Here is an example using moment.js:

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

const pacificTime = moment.tz("2021-10-25 12:00:00", "America/Los_Angeles");
const easternTime = pacificTime.clone().tz("America/New_York").format("YYYY-MM-DD HH:mm:ss");

console.log(`Pacific Time: ${pacificTime.format("YYYY-MM-DD HH:mm:ss")}`);
console.log(`Eastern Time: ${easternTime}`);
336 chars
8 lines

In this example, we first create a moment object representing the Pacific time with the America/Los_Angeles time zone. Then we clone the moment object and convert it to the Eastern time zone (America/New_York) using the tz() method. Finally, we format the Eastern time and display both times in the console.

Alternatively, here is an example using date-fns:

index.ts
import { utcToZonedTime, format } from 'date-fns-tz';

const pacificTime = "2021-10-25 12:00:00";
const easternTime = format(utcToZonedTime(pacificTime, "America/Los_Angeles"), "yyyy-MM-dd HH:mm:ss", { timeZone: "America/New_York" });

console.log(`Pacific Time: ${pacificTime}`);
console.log(`Eastern Time: ${easternTime}`);
326 chars
8 lines

In this example, we first define the Pacific time as a string. Then we use the utcToZonedTime() function from the date-fns-tz library to convert the Pacific time to a Date object in the Pacific time zone. We then format the Eastern time as a string using the format() function and passing in the Date object and the America/New_York time zone. The timeZone option specifies the time zone to use for formatting the date. Finally, we display both times in the console.

gistlibby LogSnag