convert gmt to eastern time in typescript

To convert a GMT (Greenwich Mean Time) date/time to Eastern Time in TypeScript, you will need to use a combination of Date object, moment.js and timezone conversion library.

First, create a JavaScript Date object with GMT time zone. Then, use moment.js to format the date and convert it to Eastern Time using the timezone conversion library.

Here is an example code demonstrating how to convert GMT to Eastern Time in TypeScript:

index.ts
import * as moment from 'moment-timezone';
import * as tz from 'moment-timezone/builds/moment-timezone-with-data';

function convertToEasternTime(gmtDateString: string): string {
  const gmtDate = new Date(gmtDateString + ' UTC');
  const easternTimezone = tz.tz.zone('America/New_York');

  const easternTime = moment(gmtDate).tz(easternTimezone).format('YYYY-MM-DD HH:mm:ss');

  return easternTime;
}

// Example usage:
const gmtDate = '2021-10-01 12:00:00';
const easternTime = convertToEasternTime(gmtDate);
console.log('Eastern Time:', easternTime);  // Output: Eastern Time: 2021-10-01 08:00:00
602 chars
17 lines

In this example, we first import moment.js and the timezone data for Eastern Time. Inside the convertToEasternTime function, we convert the GMT date string to a JavaScript Date object with GMT time zone. Then, we get the Eastern Timezone information from the moment-timezone library using the zone() method. Finally, we use moment.js to format the date and time with the Eastern Timezone information.

Note: The above example assumes that the input GMT date string is in ISO 8601 format. You may need to adjust the format string according to your specific input date format.

gistlibby LogSnag