convert alaska time to gmt in typescript

To convert Alaska Time to GMT in TypeScript, we can use the moment-timezone library or the date-fns library.

Using moment-timezone:

index.ts
import moment from 'moment-timezone';
    
const alaskaTime = moment.tz('America/Anchorage');
const gmtTime = alaskaTime.clone().tz('Etc/GMT');

console.log(alaskaTime.format()); // outputs: "2021-06-07T14:30:00-08:00"
console.log(gmtTime.format()); // outputs: "2021-06-07T22:30:00+00:00"
290 chars
8 lines

Using date-fns:

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

const alaskaTime = new Date();
const gmtTime = utcToZonedTime(alaskaTime, 'Etc/GMT');

console.log(format(alaskaTime, 'yyyy-MM-dd HH:mm:ssXXX')); // outputs: "2021-06-07 14:30:00-08:00"
console.log(format(gmtTime, 'yyyy-MM-dd HH:mm:ssXXX')); // outputs: "2021-06-07 22:30:00+00:00"
337 chars
8 lines

Note that moment-timezone requires the time zone name as an argument, while date-fns requires the time zone abbreviation. In both cases, Etc/GMT represents GMT time.

gistlibby LogSnag