convert hawaii time to gmt in typescript

To convert Hawaiian Time (Hawaii–Aleutian Standard Time, HST) to Greenwich Mean Time (GMT), we need to first get the respective UTC offsets for both time zones. Hawaii Standard Time is 10 hours behind Coordinated Universal Time (UTC-10), while Greenwich Mean Time is equal to Coordinated Universal Time (UTC+0).

Here's a TypeScript function that takes a date/time string in Hawaiian Time as input, and returns the equivalent date/time in GMT:

index.ts
function convertToGMT(hawaiiDateTime: string): string {
  // create a new Date object for the input date/time string in Hawaiian Time
  const hawaiiDate = new Date(hawaiiDateTime + ' GMT-1000');

  // get the UTC time by adding the UTC offset for Hawaii Standard Time (UTC-10)
  const utcTime = new Date(hawaiiDate.getTime() + (hawaiiDate.getTimezoneOffset() * 60 * 1000) + (10 * 60 * 60 * 1000));

  // format the UTC time as a string in the desired format (e.g. YYYY-MM-DDTHH:mm:ssZ)
  const gmtDateTime = utcTime.toISOString();

  return gmtDateTime;
}
556 chars
13 lines

Example usage:

index.ts
const hawaiiTime = '2021-06-22T12:30:00';
const gmtTime = convertToGMT(hawaiiTime);

console.log(gmtTime); // output: '2021-06-22T22:30:00.000Z'
145 chars
5 lines

Note that the toISOString() method returns a UTC string with a 'Z' suffix denoting the timezone offset of +00:00 (GMT/UTC).

gistlibby LogSnag