I want to convert a duration of time, i.e., number of seconds to colon-separated time string (hh:mm:ss)
I found some useful answers here but they all talk about conv
It's pretty easy,
function toTimeString(seconds) {
return (new Date(seconds * 1000)).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0];
}
To get the time part in the format hh:MM:ss
, you can use this regular expression:
(This was mentioned above in same post by someone, thanks for that.)
var myDate = new Date().toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
console.log(myDate)
Here's how I did it. It seems to work fairly well, and it's extremely compact. (It uses a lot of ternary operators, though)
function formatTime(seconds) {
var hh = Math.floor(seconds / 3600),
mm = Math.floor(seconds / 60) % 60,
ss = Math.floor(seconds) % 60;
return (hh ? (hh < 10 ? "0" : "") + hh + ":" : "") + ((mm < 10) && hh ? "0" : "") + mm + ":" + (ss < 10 ? "0" : "") + ss
}
...and for formatting strings...
String.prototype.toHHMMSS = function() {
formatTime(parseInt(this, 10))
};
Easiest way to do it.
new Date(sec * 1000).toISOString().substr(11, 8)
const secondsToTime = (seconds, locale) => {
const date = new Date(0);
date.setHours(0, 0, seconds, 0);
return date.toLocaleTimeString(locale);
}
console.log(secondsToTime(3610, "en"));
where the locale parameter ("en", "de", etc.) is optional
String.prototype.toHHMMSS = function () {
var sec_num = parseInt(this, 10); // don't forget the second param
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {hours = "0"+hours;}
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
return hours+':'+minutes+':'+seconds;
}
You can use it now like:
alert("5678".toHHMMSS());
Working snippet:
String.prototype.toHHMMSS = function () {
var sec_num = parseInt(this, 10); // don't forget the second param
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {hours = "0"+hours;}
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
return hours + ':' + minutes + ':' + seconds;
}
console.log("5678".toHHMMSS());