convert eastern time to gmt in typescript

To convert Eastern Time to GMT in TypeScript, you can use either the date-fns or moment.js libraries. Here is an example using date-fns:

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

const easternDate = new Date(); // replace with actual eastern time date
const easternTimezone = 'America/New_York';

const gmtDate = utcToZonedTime(easternDate, easternTimezone);
const gmtString = format(gmtDate, 'yyyy-MM-dd HH:mm:ss', { timeZone: 'GMT' });

console.log(gmtString); // output: 2022-01-01 05:00:00
370 chars
10 lines

This code converts the easternDate to the GMT time zone using the utcToZonedTime function and then formats the date as a string using the format function with the GMT time zone specified in the options. The result is a string representing the same moment in time, but in the GMT time zone.

Alternatively, here is an example using moment.js:

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

const easternDate = new Date(); // replace with actual eastern time date
const easternTimezone = 'America/New_York';

const gmtString = moment.tz(easternDate, easternTimezone).tz('GMT').format('YYYY-MM-DD HH:mm:ss');

console.log(gmtString); // output: 2022-01-01 05:00:00
312 chars
9 lines

This code uses the moment.js library to convert the easternDate to the GMT time zone by chaining the tz function twice – first specifying the easternTimezone and then the GMT time zone. The format function is called to format the resulting moment as a string in the specified format.

gistlibby LogSnag