Home > Software design >  UTC Offset in Seconds to Date in Javascript
UTC Offset in Seconds to Date in Javascript

Time:05-27

i've been working with an api that returns the time in an UTC offset like '7000' in seconds, im trying to pass to a date like '2020-01-01T01:56:40.000Z' or time like '1:12:03 PM'

i have tried this but returns a wrong date, as if i was giving it a value in ms


var utcSeconds = 7000;
var d = new Date(7000); 

console.log(d);  // 1970-01-01T00:00:07.000Z


All i've been able see online is the oposite proccedure or different procedure, hope you can help me, Thanks!

CodePudding user response:

One way to do this is to find a canonical IANA timezone that matches the UTC offset you get from the API. These look like 'Etc/GMT-9' and have a fixed UTC offset. (See List of tz database timezones)

Once we have this timezone we can use Date.toLocaleTimeString() to format the local time.

We can wrap all this up in a function formatLocalTime() that will display the time at that UTC offset.

function getIANATimezone(utcOffsetSeconds) {
    const utcOffsetHours = Math.abs(utcOffsetSeconds / 3600);
    const sign = (utcOffsetSeconds < 0 ) ? ' ': '-';
    return `Etc/GMT${sign}${utcOffsetHours}`;
}

function formatLocalTime(utcOffsetSeconds) {
    const timeZone = getIANATimezone(utcOffsetSeconds);
    return new Date().toLocaleTimeString('en-US', { timeZone });
}

const utcOffsets = [32400,-25200, 0, 3600];
console.log('UTC Offset(s)\tLocal time')
for(let utcOffset of utcOffsets) {
    console.log(utcOffset   '', '\t\t', formatLocalTime(utcOffset))
}
.as-console-wrapper { max-height: 100% !important; }

  • Related