I have this issue an API return me the timezone in seconds like for example: -10800, i don't know how to turn this to hours and minutes to know the exact time of that particular country.
I really apreciate the help!
CodePudding user response:
Not sure if there are pre-defined functions to help you but you can use the following code to convert seconds to hours and minutes:
//sec = 10800;
let hours = Math.floor(sec / 3600); // get hours
let minutes = Math.floor((sec - (hours * 3600)) / 60); // get minutes
let seconds = sec - (hours * 3600) - (minutes * 60); // in case you also need seconds
P.S. - While I don't know how you are getting the time zone in seconds but you should go through the time and date related functions on MDN for a cleaner solution (if not done already): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
CodePudding user response:
Your question is slightly unclear on your expected result so I just use the seconds you provided and output a string of the time using a few options:
let seconds = -10800;
let date = new Date(0);
date.setSeconds(seconds);
let timeString = date.toISOString().substr(11, 8);
console.log(timeString)
// a UTC example
const aDateNow = new Date();
aDateNow.setSeconds(seconds);
console.log(aDateNow.toUTCString());
//Using:
// Date.UTC(year, month, day, hour, minute, second)
// a UTC example, using a 0 date
const aDateNow2 = new Date(Date.UTC(0, 0, 0, 0, 0, seconds));
//aDateNow.setSeconds(seconds);
console.log(aDateNow2.toUTCString());
// just the time
console.log(aDateNow2.toUTCString().substr(17, 12));