0

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!

2
  • 1
    I'm confused by what you're trying to achieve. What does "returns the time in an UTC offset in seconds" mean? What is your expected output? What should yourfn('2020-01-01T01:56:40.000Z') or yourfn('1:12:03 PM') return? Commented May 24, 2022 at 23:46
  • The Api is returning '32400' as timezone for Tokyo,Japan right now, im trying to convert that preferably to a format time like '1:12:03 PM' Commented May 24, 2022 at 23:55

1 Answer 1

1

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; }

Sign up to request clarification or add additional context in comments.

3 Comments

Hello, i've tried your code but im always receiving the global UTC time, and not the local time for a certain offset on some city around the world. i might have misunterstood the code or something, stil i really apreciate your answer thank you so much for your time
Thanks for testing the code! What OS / Browser are you testing this on? Is the function formatLocalTime(32400) showing you UTC time? Thanks!
Hey, After reading your comment whether where i tested your code, it seems like that was the issue, i was using a Online Text Editor for quick testing, but after testing on my Node.js server it works perfectly fine, Again, thank you for taking your time!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.