convert gmt to australian western time in typescript

To convert from GMT (Greenwich Mean Time) to Australian Western Time, we can use Moment.js and Moment Timezone libraries. Here's an example of how to do it in TypeScript:

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

const gmtDate = new Date('2022-01-01T12:00:00Z'); // create a GMT date
const awtDate = moment(gmtDate).tz('Australia/Perth').toDate(); // convert to AWT date

console.log(awtDate); // output: 2022-01-01T20:00:00.000Z
261 chars
7 lines

Explanation:

  • First, we create a Date object with the GMT time '2022-01-01T12:00:00Z' (note the Z at the end which stands for Zulu time, or GMT).
  • Next, we use Moment.js to create a moment object from the GMT date by calling the moment() function with the GMT date passed as an argument.
  • Then, we use the tz() function to convert the moment object to the AWT timezone by passing 'Australia/Perth' as an argument. Note that the 'Australia/Perth' timezone identifier is specific to Moment Timezone library and corresponds to Australian Western Standard Time (AWST).
  • Finally, we call the toDate() function to convert the moment object back to a Date object with the AWT time.

The resulting AWT date is 2022-01-01T20:00:00.000Z, which is 8 hours ahead of the GMT date.

gistlibby LogSnag