convert australian western time to gmt in typescript

To convert Australian Western Time (AWST) to Greenwich Mean Time (GMT) using TypeScript, you can make use of popular time manipulation libraries such as Moment.js or date-fns.

Here's an example using Moment.js:

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

const auWestTime = "2021-05-31 12:00:00"; // AWST time
const gmtTime = moment.tz(auWestTime, "Australia/Perth").utc().format(); // GMT time

console.log(gmtTime); // Output: 2021-05-31T04:00:00Z
234 chars
7 lines

In the example above, we first import Moment.js and specify the AWST time we want to convert. We then use Moment.js to convert the time to UTC, which is equivalent to GMT, and format the result using the format() method. The resulting gmtTime variable will be a string in ISO 8601 format, representing the time in GMT.

Alternatively, you can use date-fns:

index.ts
import { parse, format } from "date-fns";
import { utcToZonedTime } from "date-fns-tz";

const auWestTime = "2021-05-31 12:00:00"; // AWST time
const gmtTime = format(utcToZonedTime(parse(auWestTime, "yyyy-MM-dd HH:mm:ss", new Date()), "Etc/GMT"), "yyyy-MM-dd'T'HH:mm:ssxxx"); // GMT time

console.log(gmtTime); // Output: 2021-05-31T04:00:00+00:00
349 chars
8 lines

In the example above, we import both the parse() and format() functions from date-fns, as well as the utcToZonedTime() function from date-fns-tz. We then parse the AWST time using parse() and convert it to a UTC time using utcToZonedTime(), specifying the timezone to convert to (in this case, "Etc/GMT", which is equivalent to GMT). Finally, we format the resulting Date object using format() to get a string in ISO 8601 format representing the time in GMT.

gistlibby LogSnag