convert gmt to eastern time in javascript

To convert GMT to Eastern Time using JavaScript, you can use the built-in Date object and its related methods.

  1. First, create a new Date object for the GMT time using new Date():
index.tsx
let gmtTime = new Date();
26 chars
2 lines
  1. Set the GMT time by passing a string with the appropriate date and time values, in ISO format (yyyy-mm-ddThh:mm:ssZ).
index.tsx
gmtTime.setUTCHours(15); // example of setting 3pm GMT
55 chars
2 lines
  1. Use the toLocaleString() method to convert the GMT time to the user’s local time zone, which will be the machine's timezone by default:
index.tsx
let estTime = new Date(gmtTime.toLocaleString());
50 chars
2 lines
  1. (optional) If you need to convert the estTime object to a specific time zone, you can set it using the setTimeZone method:
index.tsx
estTime.setTimeZone('America/New_York'); // set Eastern Time zone
66 chars
2 lines

Here's the complete code snippet:

index.tsx
let gmtTime = new Date();
gmtTime.setUTCHours(15); // example of setting 3pm GMT
let estTime = new Date(gmtTime.toLocaleString());
estTime.setTimeZone('America/New_York'); // set Eastern Time zone

console.log('GMT Time: ' + gmtTime.toISOString()); // GMT Time: 2021-10-19T15:00:00.000Z
console.log('Eastern Time: ' + estTime.toLocaleString()); // Eastern Time: 10/19/2021, 11:00:00 AM
386 chars
8 lines

Note: The Eastern Time zone uses daylight saving time, so you may need to adjust the code accordingly depending on the time of year.

gistlibby LogSnag