convert est time to gmt in typescript

To convert EST (Eastern Standard Time) to GMT (Greenwich Mean Time) in TypeScript, you can use the toLocaleString method on the Date object along with the timeZone and hour12 options. Here is an example function to convert EST to GMT:

index.ts
function convertEstToGmt(date: Date): string {
  const estTime = date.toLocaleString('en-US', { timeZone: 'America/New_York', hour12: false });
  const gmtTime = new Date(estTime).toISOString();
  return gmtTime;
}
215 chars
6 lines

This function takes in a Date object in EST timezone and returns a string value in GMT timezone. The toLocaleString method is used to convert the date to a string in EST timezone, with the timeZone option set to 'America/New_York' and hour12 option set to false. This returns a string in the format MM/DD/YYYY, HH:mm:ss.

The resulting EST time string is then used to create a new Date object and the toISOString method is called on it to return a string value in GMT timezone. This string is in ISO 8601 format (YYYY-MM-DDTHH:mm:ssZ), which represents the same moment in time as the original EST time.

You can call this function with a Date object representing EST time to get the equivalent time in GMT:

index.ts
const estDate = new Date('2022-01-01T12:00:00-05:00');
const gmtDate = convertEstToGmt(estDate);
console.log(gmtDate); // "2022-01-01T17:00:00.000Z"
149 chars
4 lines

In this example, the input Date object represents noon on January 1st, 2022 in EST timezone (-05:00 offset from GMT). The output string represents the same moment in time in GMT timezone (+00:00 offset from GMT), which is 5 hours ahead of EST.

gistlibby LogSnag