convert australian western time to gmt in javascript

To convert Australian Western Time (AWST) to Greenwich Mean Time (GMT) in JavaScript, we can use the Moment.js library. Moment.js is a popular JavaScript library for parsing, validating, manipulating, and formatting dates and times.

Here's an example code snippet that shows how to convert an AWST date/time string to a GMT date/time string using Moment.js:

index.tsx
// Load the Moment.js library
const moment = require('moment-timezone');

// Define the AWST date/time string
const awstDateTime = '2021-08-01 12:00:00';

// Create a Moment.js object from the AWST date/time string
const awstMoment = moment.tz(awstDateTime, 'Australia/Perth');

// Convert the AWST Moment.js object to a GMT string
const gmtDateTime = awstMoment.utc().format('YYYY-MM-DD HH:mm:ss');

console.log(`AWST: ${awstDateTime}`); // AWST: 2021-08-01 12:00:00
console.log(`GMT: ${gmtDateTime}`);   // GMT: 2021-08-01 04:00:00
534 chars
15 lines

In this example, we first load the Moment.js library by requiring it. We then define the AWST date/time string as 2021-08-01 12:00:00.

Next, we create a Moment.js object from the AWST date/time string using the moment.tz() function, which takes two parameters: the date/time string and the timezone identifier. In this case, the timezone identifier is 'Australia/Perth'.

We then convert the AWST Moment.js object to a GMT string using the utc() function to convert the Moment.js object to UTC/GMT time and the format() function to format the date/time string in the desired format ('YYYY-MM-DD HH:mm:ss').

Finally, we log both the AWST and GMT date/time strings to the console for verification.

Note that Moment.js uses the IANA Time Zone database, which is a comprehensive and reliable source of timezone information. Keep in mind that timezones can be complex and may change due to daylight saving time or other factors, so it's important to use a reliable library like Moment.js when working with dates and times.

gistlibby LogSnag