convert gmt to alaska time in typescript

To convert GMT to Alaska Time in TypeScript, we can make use of moment.js library which provides utilities to handle dates and timezones.

First, we need to install moment.js and timezone packages using the following command:

index.ts
npm install moment moment-timezone
35 chars
2 lines

After installing the packages, we can use the following code snippet to convert GMT to Alaska Time:

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

// convert GMT to Alaska Time
const date = new Date('2022-09-30T05:30:00.000Z');
const alaskaTime = moment(date)
                  .tz('America/Anchorage')
                  .format('YYYY-MM-DD HH:mm:ss');

console.log(alaskaTime); // output: 2022-09-29 21:30:00
302 chars
10 lines

In the above code, we are creating a new date object with GMT time and passing it to moment library's tz function to convert it to the Alaska Time timezone. Finally, we are formatting the date into the desired format and logging it to the console.

Note: Make sure to pass the Z at the end of the input date string, indicating it's a UTC time. This will help the moment library to parse the date correctly.

gistlibby LogSnag