convert australian western daylight time to gmt in typescript

To convert Australian Western Daylight Time (AWDT) to Greenwich Mean Time (GMT) in TypeScript, we can use the Moment.js library. The following code demonstrates how to perform this conversion:

index.ts
import moment from 'moment-timezone';

const awdtDate = moment.tz('2021-07-10 14:30', 'Australia/Perth');
const gmtDate = awdtDate.clone().tz('Etc/GMT');

console.log(`AWDT: ${awdtDate.format()}`); // AWDT: 2021-07-10T14:30:00+08:00
console.log(`GMT: ${gmtDate.format()}`); // GMT: 2021-07-10T06:30:00+00:00
308 chars
8 lines

We start by importing the Moment.js library and then create a moment object that represents our AWDT date and time. We specify the timezone of our date using the tz method, which takes a string argument representing the timezone name. In this case, we use the timezone name for Perth, Australia (Australia/Perth).

Next, we clone our AWDT date object and convert it to the GMT timezone by calling the tz method again, this time with the Etc/GMT timezone name.

Finally, we log both the AWDT and GMT dates to the console using the format method to display them in ISO 8601 format.

Note that we use the clone method to avoid modifying our original AWDT date object. Additionally, we use the moment object's default behavior to maintain fractions of a second in our date object. If you wish to truncate your date object to seconds, you may use the startOf('second') method on your moment objects before modification.

gistlibby LogSnag