convert new zealand time to gmt in typescript

To convert New Zealand Time (NZT) to Greenwich Mean Time (GMT) in TypeScript, you can use the following function:

index.ts
function convertNztToGmt(date: Date): Date {
  const nztOffset = 720; // NZT is UTC+12
  const gmtOffset = 0; // GMT is UTC+0
  const offsetDiff = nztOffset - gmtOffset;
  const newDate = new Date(date.getTime() - offsetDiff * 60 * 1000);
  return newDate;
}
259 chars
8 lines

The function takes a Date object representing a time in NZT and returns a new Date object representing the equivalent time in GMT.

The function works by calculating the difference between the NZT offset from UTC (which is +12 hours) and the GMT offset from UTC (which is 0 hours). It then subtracts this difference from the input Date object's time in milliseconds and creates a new Date object representing the new time in GMT.

Example usage:

index.ts
const nztDate = new Date('2021-06-30T12:34:56+12:00');
const gmtDate = convertNztToGmt(nztDate);
console.log(gmtDate.toISOString()); // Output: 2021-06-30T00:34:56.000Z
169 chars
4 lines

In this example, the input Date object represents a time of 12:34:56 PM on June 30, 2021 in NZT. The output Date object represents the equivalent time in GMT, which is 12:34:56 AM on the same day. The output is in ISO 8601 format.

gistlibby LogSnag