convert gmt to alaska time in javascript

To convert GMT to Alaska time in JavaScript, first, we need to get the current date and time in GMT timezone. We can use the Date() constructor to create a new date object in GMT timezone. Then we can convert this date to Alaska timezone using the toLocaleString() method with the timeZone option set to 'America/Anchorage'. Here's an example code snippet:

index.tsx
// create a new date object in GMT timezone
let date = new Date();

// convert date to Alaska timezone
let alaskaTime = date.toLocaleString('en-US', { timeZone: 'America/Anchorage' });

console.log('GMT time:', date.toUTCString());
console.log('Alaska time:', alaskaTime);
273 chars
9 lines

In this code, we first create a new Date() object in GMT timezone. We then use the toLocaleString() method with the timeZone option set to 'America/Anchorage' to convert this date to Alaska timezone. Finally, we log the original GMT time and the converted Alaska time to the console.

Note that the toLocaleString() method returns a string in the format "MM/DD/YYYY, hh:mm:ss AM/PM". If you want to extract the date and time components separately, you can use the toLocaleDateString() and toLocaleTimeString() methods with the same timeZone option.

gistlibby LogSnag