convert new zealand time to gmt in javascript

To convert New Zealand time to GMT in JavaScript, you first need to create a Date object with the New Zealand time and then convert it to the GMT time zone.

Here's the code:

index.tsx
// Get the current date and time in New Zealand
const nzTime = new Date();

// Get the offset of New Zealand time zone from UTC in minutes
const nzOffset = nzTime.getTimezoneOffset();

// Convert to GMT by adding the offset
const gmtTime = new Date(nzTime.getTime() + nzOffset * 60 * 1000);

// Print the GMT time in ISO format
console.log(gmtTime.toISOString());
364 chars
12 lines

In this code, we first create a new Date object nzTime which represents the current date and time in the New Zealand time zone. We then get the offset of the New Zealand time zone from UTC in minutes using the getTimezoneOffset() method of the Date object.

We convert the New Zealand time to GMT by adding the offset nzOffset to the original time in milliseconds, which is equal to nzTime.getTime() + nzOffset * 60 * 1000.

Finally, we create a new Date object gmtTime with the GMT time and print it in ISO format using the toISOString() method.

gistlibby LogSnag