To determine the current time for a specific UTC offset, one can add it to the current UTC time using the Date constructor along with various getUTC..() functions to extract the time components.
It is important to note that fixed UTC offsets should be used with caution, especially for places like New York where the UTC offset may change due to Daylight Saving Time. Therefore, the correct UTC offset must be applied according to the specific moment in time.
When retrieving time information from an API with a UTC Offset (or Timezone Number), assuming that the UTC offset remains constant for a location would not be advisable.
function getTimeComponentsFromUTCOffset(timeMillis, utcOffsetSeconds) {
const d = new Date(timeMillis + utcOffsetSeconds * 1000);
return {
year: d.getUTCFullYear(),
month: d.getUTCMonth() + 1,
day: d.getUTCDate(),
hour: d.getUTCHours(),
minute: d.getUTCMinutes(),
second: d.getUTCSeconds()
};
}
// NB: timeZoneNumber or UTC offset will vary according to local DST rules...
const inputs = [
{ timeZoneNumber: +28800, location: 'Perth' },
{ timeZoneNumber: +19800, location: 'Delhi' },
{ timeZoneNumber: +3600, location: 'London' },
{ timeZoneNumber: -14400, location: 'New York' },
]
console.log('Location'.padEnd(12), 'Year ', 'Month ', 'Day ', 'Hour ', 'Minute', 'Second');
for(let input of inputs) {
let time = getTimeComponentsFromUTCOffset(Date.now(), input.timeZoneNumber);
console.log(input.location.padEnd(12), ...Object.values(time).map(s => (s + '').padStart(2, '0').padEnd(6)));
}
.as-console-wrapper { max-height: 100% !important; }