Turning an input (amount of seconds) into an HH:MM:SS format for from API [duplicate] - javascript

How can I convert seconds to an HH-MM-SS string using JavaScript?

You can manage to do this without any external JavaScript library with the help of JavaScript Date method like following:
const date = new Date(null);
date.setSeconds(SECONDS); // specify value for SECONDS here
const result = date.toISOString().slice(11, 19);
Or, as per #Frank's comment; a one liner:
new Date(SECONDS * 1000).toISOString().slice(11, 19);

Updated (2020):
Please use #Frank's one line solution:
new Date(SECONDS * 1000).toISOString().substring(11, 16)
If SECONDS<3600 and if you want to show only MM:SS then use below code:
new Date(SECONDS * 1000).toISOString().substring(14, 19)
It is by far the best solution.
Old answer:
Use the Moment.js library.

I don't think any built-in feature of the standard Date object will do this for you in a way that's more convenient than just doing the math yourself.
hours = Math.floor(totalSeconds / 3600);
totalSeconds %= 3600;
minutes = Math.floor(totalSeconds / 60);
seconds = totalSeconds % 60;
Example:
let totalSeconds = 28565;
let hours = Math.floor(totalSeconds / 3600);
totalSeconds %= 3600;
let minutes = Math.floor(totalSeconds / 60);
let seconds = totalSeconds % 60;
console.log("hours: " + hours);
console.log("minutes: " + minutes);
console.log("seconds: " + seconds);
// If you want strings with leading zeroes:
minutes = String(minutes).padStart(2, "0");
hours = String(hours).padStart(2, "0");
seconds = String(seconds).padStart(2, "0");
console.log(hours + ":" + minutes + ":" + seconds);

I know this is kinda old, but...
ES2015:
var toHHMMSS = (secs) => {
var sec_num = parseInt(secs, 10)
var hours = Math.floor(sec_num / 3600)
var minutes = Math.floor(sec_num / 60) % 60
var seconds = sec_num % 60
return [hours,minutes,seconds]
.map(v => v < 10 ? "0" + v : v)
.filter((v,i) => v !== "00" || i > 0)
.join(":")
}
It will output:
toHHMMSS(129600) // 36:00:00
toHHMMSS(13545) // 03:45:45
toHHMMSS(180) // 03:00
toHHMMSS(18) // 00:18

As Cleiton pointed out in his answer, moment.js can be used for this:
moment().startOf('day')
.seconds(15457)
.format('H:mm:ss');

Here's a simple function for converting times that might help
function formatSeconds(seconds) {
var date = new Date(1970,0,1);
date.setSeconds(seconds);
return date.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
}

This does the trick:
function secondstotime(secs)
{
var t = new Date(1970,0,1);
t.setSeconds(secs);
var s = t.toTimeString().substr(0,8);
if(secs > 86399)
s = Math.floor((t - Date.parse("1/1/70")) / 3600000) + s.substr(2);
return s;
}
(Sourced from here)

var timeInSec = "661"; //even it can be string
String.prototype.toHHMMSS = function () {
/* extend the String by using prototypical inheritance */
var seconds = parseInt(this, 10); // don't forget the second param
var hours = Math.floor(seconds / 3600);
var minutes = Math.floor((seconds - (hours * 3600)) / 60);
seconds = seconds - (hours * 3600) - (minutes * 60);
if (hours < 10) {hours = "0"+hours;}
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
var time = hours+':'+minutes+':'+seconds;
return time;
}
alert("5678".toHHMMSS()); // "01:34:38"
console.log(timeInSec.toHHMMSS()); //"00:11:01"
we can make this function lot shorter and crisp but that decreases the readability, so we will write it as simple as possible and as stable as possible.
or you can check this working here:

Try this:
function toTimeString(seconds) {
return (new Date(seconds * 1000)).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0];
}

I think the most general (and cryptic) solution could be this
function hms(seconds) {
return [3600, 60]
.reduceRight(
(pipeline, breakpoint) => remainder =>
[Math.floor(remainder / breakpoint)].concat(pipeline(remainder % breakpoint)),
r => [r]
)(seconds)
.map(amount => amount.toString().padStart(2, '0'))
.join('-');
}
Or to copy & paste the shortest version
function hms(seconds) {
return [3600, 60]
.reduceRight(
(p, b) => r => [Math.floor(r / b)].concat(p(r % b)),
r => [r]
)(seconds)
.map(a => a.toString().padStart(2, '0'))
.join('-');
}
Some example outputs:
> hms(0)
< "00-00-00"
> hms(5)
< "00-00-05"
> hms(60)
< "00-01-00"
> hms(3785)
< "01-03-05"
> hms(37850)
< "10-30-50"
> hms(378500)
< "105-08-20"
How it works
Algorithm
To get hours you divide total seconds by 3600 and floor it.
To get minutes you divide remainder by 60 and floor it.
To get seconds you just use the remainder.
It would also be nice to keep individual amounts in an array for easier formatting.
For example given the input of 3785s the output should be [1, 3, 5], that is 1 hour, 3 minutes and 5 seconds.
Creating pipeline
Naming the 3600 and 60 constants "breakpoints" you can write this algorithm into function as this
function divideAndAppend(remainder, breakpoint, callback) {
return [Math.floor(remainder / breakpoint)].concat(callback(remainder % breakpoint));
}
It returns an array where first item is the amount for given breakpoint and the rest of the array is given by the callback.
Reusing the divideAndAppend in callback function will give you a pipeline of composed divideAndAppend functions. Each one of these
computes amount per given breakpoint and append it to the array making your desired output.
Then you also need the "final" callback that ends this pipeline. In another words you used all breakpoints and now you have only the remainder.
Since you have already the answer at 3) you should use some sort of identity function, in this case remainder => [remainder].
You can now write the pipeline like this
let pipeline = r3 => divideAndAppend(
r3,
3600,
r2 => divideAndAppend(
r2,
60,
r1 => [r1]));
> pipeline(3785)
< [1, 3, 5]
Cool right?
Generalizing using for-loop
Now you can generalize with a variable amount of breakpoints and create a for-loop that will compose individial divideAndAppend functions into
the pipeline.
You start with the identity function r1 => [r1], then use the 60 breakpoint and finally use the 3600 breakpoint.
let breakpoints = [60, 3600];
let pipeline = r => [r];
for (const b of breakpoints) {
const previousPipeline = pipeline;
pipeline = r => divideAndAppend(r, b, previousPipeline);
}
> pipeline(3785)
< [1, 3, 5]
Using Array.prototype.reduce()
Now you can rewrite this for-loop into reducer for shorter and more functional code. In other words rewrite function composition into the reducer.
let pipeline = [60, 3600].reduce(
(ppln, b) => r => divideAndAppend(r, b, ppln),
r => [r]
);
> pipeline(3785)
< [1, 3, 5]
The accumulator ppln is the pipeline and you are composing it using the previous version of it. The initial pipeline is r => [r].
You can now inline the function divideAndAppend and use Array.prototype.reduceRight which is the same as [].reverse().reduce(...) to make the breakpoints
definitions more natural.
let pipeline = [3600, 60]
.reduceRight(
(ppln, b) => r => [Math.floor(r / b)].concat(ppln(r % b)),
r => [r]
);
Which is the final form. Then you just appy mapping to string with padded 0's on left and join the strings with : separator;
More generalizations
Wrapping the reducer into function
function decompose(total, breakpoints) {
return breakpoints.reduceRight(
(p, b) => r => [Math.floor(r / b)].concat(p(r % b)),
r => [r]
)(total);
}
> decompose(3785, [3600, 60])
< [1, 3, 5]
you now have very general algorithm you can work with. For example:
Convert easily (the weird) us length standards
Given the standards
Unit
Divisions
1 foot
12 inches
1 yard
3 feet
1 mile
1760 yards
> decompose(123_456, [1760 * 3 * 12, 3 * 12, 12])
< [1, 1669, 1, 0]
123456 in = 1 mi, 1669 yd, 1 feet and 0 in
Or you can somewhat convert to decimal or binary representations
> decompose(123_456, [100_000, 10_000, 1000, 100, 10])
< [1, 2, 3, 4, 5, 6]
> decompose(127, [128, 64, 32, 16, 8, 4, 2])
< [0, 1, 1, 1, 1, 1, 1, 1]
Works also with floating point breakpoints
Since Javascript supports mod operator with floating point numbers, you can also do
> decompose(26.5, [20, 2.5])
< [1, 2, 1.5]
The edge case of no breakpoints is also naturally covered
> decompose(123, [])
< [123]

Here is an extension to Number class. toHHMMSS() converts seconds to an hh:mm:ss string.
Number.prototype.toHHMMSS = function() {
var hours = Math.floor(this / 3600) < 10 ? ("00" + Math.floor(this / 3600)).slice(-2) : Math.floor(this / 3600);
var minutes = ("00" + Math.floor((this % 3600) / 60)).slice(-2);
var seconds = ("00" + (this % 3600) % 60).slice(-2);
return hours + ":" + minutes + ":" + seconds;
}
// Usage: [number variable].toHHMMSS();
// Here is a simple test
var totalseconds = 1234;
document.getElementById("timespan").innerHTML = totalseconds.toHHMMSS();
// HTML of the test
<div id="timespan"></div>

Easy to follow version for noobies:
var totalNumberOfSeconds = YOURNUMBEROFSECONDS;
var hours = parseInt( totalNumberOfSeconds / 3600 );
var minutes = parseInt( (totalNumberOfSeconds - (hours * 3600)) / 60 );
var seconds = Math.floor((totalNumberOfSeconds - ((hours * 3600) + (minutes * 60))));
var result = (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + seconds : seconds);
console.log(result);

This function should do it :
var convertTime = function (input, separator) {
var pad = function(input) {return input < 10 ? "0" + input : input;};
return [
pad(Math.floor(input / 3600)),
pad(Math.floor(input % 3600 / 60)),
pad(Math.floor(input % 60)),
].join(typeof separator !== 'undefined' ? separator : ':' );
}
Without passing a separator, it uses : as the (default) separator :
time = convertTime(13551.9941351); // --> OUTPUT = 03:45:51
If you want to use - as a separator, just pass it as the second parameter:
time = convertTime(1126.5135155, '-'); // --> OUTPUT = 00-18-46
See also this Fiddle.

Chiming in on this old thread -- the OP stated HH:MM:SS, and many of the solutions work, until you realize you need more than 24 hours listed. And maybe you don't want more than a single line of code. Here you go:
d=(s)=>{f=Math.floor;g=(n)=>('00'+n).slice(-2);return f(s/3600)+':'+g(f(s/60)%60)+':'+g(s%60)}
It returns H+:MM:SS. To use it, simply use:
d(91260); // returns "25:21:00"
d(960); // returns "0:16:00"
...I tried to get it to use the least amount of code possible, for a nice one-liner approach.

For the special case of HH:MM:SS.MS (eq: "00:04:33.637") as used by FFMPEG to specify milliseconds.
[-][HH:]MM:SS[.m...]
HH expresses the number of hours, MM the number of minutes for a
maximum of 2 digits, and SS the number of seconds for a maximum of 2
digits. The m at the end expresses decimal value for SS.
/* HH:MM:SS.MS to (FLOAT)seconds ---------------*/
function timerToSec(timer){
let vtimer = timer.split(":")
let vhours = +vtimer[0]
let vminutes = +vtimer[1]
let vseconds = parseFloat(vtimer[2])
return vhours * 3600 + vminutes * 60 + vseconds
}
/* Seconds to (STRING)HH:MM:SS.MS --------------*/
function secToTimer(sec){
let o = new Date(0)
let p = new Date(sec*1000)
return new Date(p.getTime()-o.getTime())
.toISOString()
.split("T")[1]
.split("Z")[0]
}
/* Example: 7hours, 4 minutes, 33 seconds and 637 milliseconds */
const t = "07:04:33.637"
console.log(
t + " => " +
timerToSec(t) +
"s"
)
/* Test: 25473 seconds and 637 milliseconds */
const s = 25473.637 // "25473.637"
console.log(
s + "s => " +
secToTimer(s)
)
Example usage, a milliseconds transport timer:
/* Seconds to (STRING)HH:MM:SS.MS --------------*/
function secToTimer(sec){
let o = new Date(0)
let p = new Date(sec*1000)
return new Date(p.getTime()-o.getTime())
.toISOString()
.split("T")[1]
.split("Z")[0]
}
let job, origin = new Date().getTime()
const timer = () => {
job = requestAnimationFrame(timer)
OUT.textContent = secToTimer((new Date().getTime() - origin) / 1000)
}
requestAnimationFrame(timer)
span {font-size:4rem}
<span id="OUT"></span>
<br>
<button onclick="origin = new Date().getTime()">RESET</button>
<button onclick="requestAnimationFrame(timer)">RESTART</button>
<button onclick="cancelAnimationFrame(job)">STOP</button>
Example usage, binded to a media element
/* Seconds to (STRING)HH:MM:SS.MS --------------*/
function secToTimer(sec){
let o = new Date(0)
let p = new Date(sec*1000)
return new Date(p.getTime()-o.getTime())
.toISOString()
.split("T")[1]
.split("Z")[0]
}
VIDEO.addEventListener("timeupdate", function(e){
OUT.textContent = secToTimer(e.target.currentTime)
}, false)
span {font-size:4rem}
<span id="OUT"></span><br>
<video id="VIDEO" width="400" controls autoplay>
<source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
</video>
Outside the question, those functions written in php:
<?php
/* HH:MM:SS to (FLOAT)seconds ------------------*/
function timerToSec($timer){
$vtimer = explode(":",$timer);
$vhours = (int)$vtimer[0];
$vminutes = (int)$vtimer[1];
$vseconds = (float)$vtimer[2];
return $vhours * 3600 + $vminutes * 60 + $vseconds;
}
/* Seconds to (STRING)HH:MM:SS -----------------*/
function secToTimer($sec){
return explode(" ", date("H:i:s", $sec))[0];
}

After looking at all the answers and not being happy with most of them, this is what I came up with. I know I am very late to the conversation, but here it is anyway.
function secsToTime(secs){
var time = new Date();
// create Date object and set to today's date and time
time.setHours(parseInt(secs/3600) % 24);
time.setMinutes(parseInt(secs/60) % 60);
time.setSeconds(parseInt(secs%60));
time = time.toTimeString().split(" ")[0];
// time.toString() = "HH:mm:ss GMT-0800 (PST)"
// time.toString().split(" ") = ["HH:mm:ss", "GMT-0800", "(PST)"]
// time.toTimeString().split(" ")[0]; = "HH:mm:ss"
return time;
}
I create a new Date object, change the time to my parameters, convert the Date Object to a time string, and removed the additional stuff by splitting the string and returning only the part that need.
I thought I would share this approach, since it removes the need for regex, logic and math acrobatics to get the results in "HH:mm:ss" format, and instead it relies on built in methods.
You may want to take a look at the documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

below is the given code which will convert seconds into hh-mm-ss format:
var measuredTime = new Date(null);
measuredTime.setSeconds(4995); // specify value of SECONDS
var MHSTime = measuredTime.toISOString().substr(11, 8);
Get alternative method from Convert seconds to HH-MM-SS format in JavaScript

var time1 = date1.getTime();
var time2 = date2.getTime();
var totalMilisec = time2 - time1;
alert(DateFormat('hh:mm:ss',new Date(totalMilisec)))
/* ----------------------------------------------------------
* Field | Full Form | Short Form
* -------------|--------------------|-----------------------
* Year | yyyy (4 digits) | yy (2 digits)
* Month | MMM (abbr.) | MM (2 digits)
| NNN (name) |
* Day of Month | dd (2 digits) |
* Day of Week | EE (name) | E (abbr)
* Hour (1-12) | hh (2 digits) |
* Minute | mm (2 digits) |
* Second | ss (2 digits) |
* ----------------------------------------------------------
*/
function DateFormat(formatString,date){
if (typeof date=='undefined'){
var DateToFormat=new Date();
}
else{
var DateToFormat=date;
}
var DAY = DateToFormat.getDate();
var DAYidx = DateToFormat.getDay();
var MONTH = DateToFormat.getMonth()+1;
var MONTHidx = DateToFormat.getMonth();
var YEAR = DateToFormat.getYear();
var FULL_YEAR = DateToFormat.getFullYear();
var HOUR = DateToFormat.getHours();
var MINUTES = DateToFormat.getMinutes();
var SECONDS = DateToFormat.getSeconds();
var arrMonths = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
var arrDay=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
var strMONTH;
var strDAY;
var strHOUR;
var strMINUTES;
var strSECONDS;
var Separator;
if(parseInt(MONTH)< 10 && MONTH.toString().length < 2)
strMONTH = "0" + MONTH;
else
strMONTH=MONTH;
if(parseInt(DAY)< 10 && DAY.toString().length < 2)
strDAY = "0" + DAY;
else
strDAY=DAY;
if(parseInt(HOUR)< 10 && HOUR.toString().length < 2)
strHOUR = "0" + HOUR;
else
strHOUR=HOUR;
if(parseInt(MINUTES)< 10 && MINUTES.toString().length < 2)
strMINUTES = "0" + MINUTES;
else
strMINUTES=MINUTES;
if(parseInt(SECONDS)< 10 && SECONDS.toString().length < 2)
strSECONDS = "0" + SECONDS;
else
strSECONDS=SECONDS;
switch (formatString){
case "hh:mm:ss":
return strHOUR + ':' + strMINUTES + ':' + strSECONDS;
break;
//More cases to meet your requirements.
}
}

I just wanted to give a little explanation to the nice answer above:
var totalSec = new Date().getTime() / 1000;
var hours = parseInt( totalSec / 3600 ) % 24;
var minutes = parseInt( totalSec / 60 ) % 60;
var seconds = totalSec % 60;
var result = (hours < 10 ? "0" + hours : hours) + "-" + (minutes < 10 ? "0" + minutes : minutes) + "-" + (seconds < 10 ? "0" + seconds : seconds);
On the second line, since there are 3600 seconds in 1 hour, we divide the total number of seconds by 3600 to get the total number of hours. We use parseInt to strip off any decimal. If totalSec was 12600 (3 and half hours), then parseInt( totalSec / 3600 ) would return 3, since we will have 3 full hours. Why do we need the % 24 in this case? If we exceed 24 hours, let's say we have 25 hours (90000 seconds), then the modulo here will take us back to 1 again, rather than returning 25. It is confining the result within a 24 hour limit, since there are 24 hours in one day.
When you see something like this:
25 % 24
Think of it like this:
25 mod 24 or what is the remainder when we divide 25 by 24

None of the answers here satisfies my requirements as I want to be able to handle
Large numbers of seconds (days), and
Negative numbers
Although those are not required by the OP, it's good practice to cover edge cases, especially when it takes little effort.
It's pretty obvious is that the OP means a NUMBER of seconds when he says seconds. Why would peg your function on String?
function secondsToTimeSpan(seconds) {
const value = Math.abs(seconds);
const days = Math.floor(value / 1440);
const hours = Math.floor((value - (days * 1440)) / 3600);
const min = Math.floor((value - (days * 1440) - (hours * 3600)) / 60);
const sec = value - (days * 1440) - (hours * 3600) - (min * 60);
return `${seconds < 0 ? '-':''}${days > 0 ? days + '.':''}${hours < 10 ? '0' + hours:hours}:${min < 10 ? '0' + min:min}:${sec < 10 ? '0' + sec:sec}`
}
secondsToTimeSpan(0); // => 00:00:00
secondsToTimeSpan(1); // => 00:00:01
secondsToTimeSpan(1440); // => 1.00:00:00
secondsToTimeSpan(-1440); // => -1.00:00:00
secondsToTimeSpan(-1); // => -00:00:01

Simple function to convert seconds into in hh:mm:ss format :
function getHHMMSSFromSeconds(totalSeconds) {
if (!totalSeconds) {
return '00:00:00';
}
const hours = Math.floor(totalSeconds / 3600);
const minutes = Math.floor(totalSeconds % 3600 / 60);
const seconds = totalSeconds % 60;
const hhmmss = padTo2(hours) + ':' + padTo2(minutes) + ':' + padTo2(seconds);
return hhmmss;
}
// function to convert single digit to double digit
function padTo2(value) {
if (!value) {
return '00';
}
return value < 10 ? String(value).padStart(2, '0') : value;
}

Here is a function to convert seconds to hh-mm-ss format based on powtac's answer here
jsfiddle
/**
* Convert seconds to hh-mm-ss format.
* #param {number} totalSeconds - the total seconds to convert to hh- mm-ss
**/
var SecondsTohhmmss = function(totalSeconds) {
var hours = Math.floor(totalSeconds / 3600);
var minutes = Math.floor((totalSeconds - (hours * 3600)) / 60);
var seconds = totalSeconds - (hours * 3600) - (minutes * 60);
// round seconds
seconds = Math.round(seconds * 100) / 100
var result = (hours < 10 ? "0" + hours : hours);
result += "-" + (minutes < 10 ? "0" + minutes : minutes);
result += "-" + (seconds < 10 ? "0" + seconds : seconds);
return result;
}
Example use
var seconds = SecondsTohhmmss(70);
console.log(seconds);
// logs 00-01-10

There are lots of options of solve this problem, and obvious there are good option suggested about, But I wants to add one more optimized code here
function formatSeconds(sec) {
return [(sec / 3600), ((sec % 3600) / 60), ((sec % 3600) % 60)]
.map(v => v < 10 ? "0" + parseInt(v) : parseInt(v))
.filter((i, j) => i !== "00" || j > 0)
.join(":");
}
if you don't wants formatted zero with less then 10 number, you can use
function formatSeconds(sec) {
return parseInt(sec / 3600) + ':' + parseInt((sec % 3600) / 60) + ':' + parseInt((sec % 3600) % 60);
}
Sample Code http://fiddly.org/1c476/1

In one line, using T.J. Crowder's solution :
secToHHMMSS = seconds => `${Math.floor(seconds / 3600)}:${Math.floor((seconds % 3600) / 60)}:${Math.floor((seconds % 3600) % 60)}`
In one line, another solution that also count days :
secToDHHMMSS = seconds => `${parseInt(seconds / 86400)}d ${new Date(seconds * 1000).toISOString().substr(11, 8)}`
Source : https://gist.github.com/martinbean/2bf88c446be8048814cf02b2641ba276

var sec_to_hms = function(sec){
var min, hours;
sec = sec - (min = Math.floor(sec/60))*60;
min = min - (hours = Math.floor(min/60))*60;
return (hours?hours+':':'') + ((min+'').padStart(2, '0')) + ':'+ ((sec+'').padStart(2, '0'));
}
alert(sec_to_hms(2442542));

Have you tried adding seconds to a Date object?
Date.prototype.addSeconds = function(seconds) {
this.setSeconds(this.getSeconds() + seconds);
};
var dt = new Date();
dt.addSeconds(1234);
A sample:
https://jsfiddle.net/j5g2p0dc/5/
Updated:
Sample link was missing so I created a new one.

You can also use below code:
int ss = nDur%60;
nDur = nDur/60;
int mm = nDur%60;
int hh = nDur/60;

For anyone using AngularJS, a simple solution is to filter the value with the date API, which converts milliseconds to a string based on the requested format. Example:
<div>Offer ends in {{ timeRemaining | date: 'HH:mm:ss' }}</div>
Note that this expects milliseconds, so you may want to multiply timeRemaining by 1000 if you are converting from seconds (as the original question was formulated).

I ran into the case some have mentioned where the number of seconds is more than a day. Here's an adapted version of #Harish Anchu's top-rated answer that accounts for longer periods of time:
function secondsToTime(seconds) {
const arr = new Date(seconds * 1000).toISOString().substr(11, 8).split(':');
const days = Math.floor(seconds / 86400);
arr[0] = parseInt(arr[0], 10) + days * 24;
return arr.join(':');
}
Example:
secondsToTime(101596) // outputs '28:13:16' as opposed to '04:13:16'

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;
}
Usage Example
alert("186".toHHMMSS());

Related

Math.trunc() not rounding values properly

I know there is most definitely a better way to do this in JavaScript but I was kind of just doing something that I know. I am doing another Code Wars challenge and seem to get 12:34:55 when I am supposed to get 12:34:56.
For the challenge the function is given input in the format of just seconds, ex. 86399, and then the output should be a human readable format of this.
I don't really know what is wrong here and feel like it has something to do with Math.trunc() as my math makes sense.
I would explain the math but it's pretty self explanatory in the code. The only issue seems to be the seconds.
function humanReadable(seconds) {
const hour = Math.trunc((seconds / 60) / 60);
const mins = Math.trunc((((seconds / 60) / 60) - hour) * 60);
const secs = Math.trunc(((seconds / 60) - Math.trunc(seconds / 60)) * 60);
return `${hour < 10 ? `0${hour}` : hour}:${mins < 10 ? `0${mins}` : mins}:${secs < 10 ? `0${secs}` : secs}`
}
The issue is due to floating point not being able to exactly represent numbers
in the case of 45296 - which is 12:34:56
A: seconds / 60 = 754.9333333333333
B: Math.trunc(seconds / 60) = 754
A - B (should be 0.9333333333333) = 0.9333333333332803
You can see, it's LESS than what it should be, but even 0.9333333333333 * 60 is 55.999999999998 ... truncate that, you get 55
One way to fix it is to
const secs = Math.round(((seconds / 60) - Math.trunc(seconds / 60)) * 60);
And, maybe also
const mins = Math.trunc((((seconds / 60) / 60) - hour) * 60);
there are over 600 cases where the minutes "fail"
Actually, don't do that, it doesn't fix the 600 or so where the minutes are wrong!
Easier way is to use modulo % operator
The results of the divisions in this code will always be "integer" only, since the divisor will always be an exact multiple of 60 once you take away the mod 60 (since that's just the remainder after dividing by 60) - Maths! :p
function humanReadable(seconds) {
const ss = seconds % 60;
seconds = (seconds - ss) / 60;
const mm = seconds % 60;
const hh = (seconds - mm) / 60;
return [hh,mm,ss].map(v => (''+v).padStart(2, 0)).join(':');
}
console.log(humanReadable(45296))
Or, you could just use a date object and let it do all the work for you
function humanReadable(seconds) {
const d = new Date(0);
d.setUTCSeconds(seconds);
const hh = d.getUTCHours().toString().padStart(2, '0');
const mm = d.getUTCMinutes().toString().padStart(2, '0');
const ss = d.getUTCSeconds().toString().padStart(2, '0');
return `${hh}:${mm}:${ss}`;
}
console.log(humanReadable(45296))
I've also included an alternative way to get the leading zeros - that's just habit for me these says to use padStart etc
before padStart was a thing, instead of
hour < 10 ? `0${hour}` : hour
I'd do
`0${hour}`.substr(-2)
But since you're using template literals, you definitely have padStart :p
You should try to use the Modulus to get the remainder after each division of the number as shown below in code snippet.
let d = 86399;
var h = Math.floor(d / 3600);
var m = Math.floor(d % 3600 / 60);
var s = Math.trunc(d % 60);
var result = `${h < 10 ? `0${h}` : h}:${m < 10 ? `0${m}` : m}:${s < 10 ? `0${s}` : s}`
console.log(result);

How to add a zero if the number of seconds is less than 10? After converting integer to minutes and seconds [duplicate]

This is a common problem but I'm not sure how to solve it. The code below works fine.
var mind = time % (60 * 60);
var minutes = Math.floor(mind / 60);
var secd = mind % 60;
var seconds = Math.ceil(secd);
However, when I get to 1 hour or 3600 seconds it returns 0 minutes and 0 seconds. How can I avoid this so it returns all the minutes?
To get the number of full minutes, divide the number of total seconds by 60 (60 seconds/minute):
const minutes = Math.floor(time / 60);
And to get the remaining seconds, multiply the full minutes with 60 and subtract from the total seconds:
const seconds = time - minutes * 60;
Now if you also want to get the full hours too, divide the number of total seconds by 3600 (60 minutes/hour · 60 seconds/minute) first, then calculate the remaining seconds:
const hours = Math.floor(time / 3600);
time = time - hours * 3600;
Then you calculate the full minutes and remaining seconds.
Bonus:
Use the following code to pretty-print the time (suggested by Dru):
function str_pad_left(string, pad, length) {
return (new Array(length + 1).join(pad) + string).slice(-length);
}
const finalTime = str_pad_left(minutes, '0', 2) + ':' + str_pad_left(seconds, '0', 2);
Another fancy solution:
function fancyTimeFormat(duration) {
// Hours, minutes and seconds
const hrs = ~~(duration / 3600);
const mins = ~~((duration % 3600) / 60);
const secs = ~~duration % 60;
// Output like "1:01" or "4:03:59" or "123:03:59"
let ret = "";
if (hrs > 0) {
ret += "" + hrs + ":" + (mins < 10 ? "0" : "");
}
ret += "" + mins + ":" + (secs < 10 ? "0" : "");
ret += "" + secs;
return ret;
}
console.log(
fancyTimeFormat(1),
fancyTimeFormat(10),
fancyTimeFormat(100),
fancyTimeFormat(1000),
fancyTimeFormat(10000),
);
~~ is a shorthand for Math.floor, see this link for more info
For people dropping in hoping for a quick simple and thus short solution to format seconds into M:SS :
function fmtMSS(s){return(s-(s%=60))/60+(9<s?':':':0')+s}
done..
The function accepts either a Number (preferred) or a String (2 conversion 'penalties' which you can halve by prepending + in the function call's argument for s as in: fmtMSS(+strSeconds)), representing positive integer seconds s as argument.
Examples:
fmtMSS( 0 ); // 0:00
fmtMSS( '8'); // 0:08
fmtMSS( 9 ); // 0:09
fmtMSS( '10'); // 0:10
fmtMSS( 59 ); // 0:59
fmtMSS( +'60'); // 1:00
fmtMSS( 69 ); // 1:09
fmtMSS( 3599 ); // 59:59
fmtMSS('3600'); // 60:00
fmtMSS('3661'); // 61:01
fmtMSS( 7425 ); // 123:45
Breakdown:
function fmtMSS(s){ // accepts seconds as Number or String. Returns m:ss
return( s - // take value s and subtract (will try to convert String to Number)
( s %= 60 ) // the new value of s, now holding the remainder of s divided by 60
// (will also try to convert String to Number)
) / 60 + ( // and divide the resulting Number by 60
// (can never result in a fractional value = no need for rounding)
// to which we concatenate a String (converts the Number to String)
// who's reference is chosen by the conditional operator:
9 < s // if seconds is larger than 9
? ':' // then we don't need to prepend a zero
: ':0' // else we do need to prepend a zero
) + s ; // and we add Number s to the string (converting it to String as well)
}
Note: Negative range could be added by prepending (0>s?(s=-s,'-'):'')+ to the return expression (actually, (0>s?(s=-s,'-'):0)+ would work as well).
2020 UPDATE
Using basic math and simple javascript this can be done in just a few lines of code.
EXAMPLE - Convert 7735 seconds to HH:MM:SS.
MATH:
Calculations use:
Math.floor() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor
The Math.floor() function returns the largest integer less than or equal to a given number.
% arithmetic operator (Remainder) - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Remainder
The remainder operator returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend.
Check out code below. Seconds are divided by 3600 to get number of hours and a remainder, which is used to calculate number of minutes and seconds.
HOURS => 7735 / 3600 = 2 remainder 535
MINUTES => 535 / 60 = 8 remainder 55
SECONDS => 55
LEADING ZEROS:
Many answers here use complicated methods to show number of hours, minutes and seconds in a proper way with leading zero - 45, 04 etc. This can be done using padStart(). This works for strings so the number must be converted to string using toString().
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
The padStart() method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of the current string.
CODE:
function secondsToTime(e){
const h = Math.floor(e / 3600).toString().padStart(2,'0'),
m = Math.floor(e % 3600 / 60).toString().padStart(2,'0'),
s = Math.floor(e % 60).toString().padStart(2,'0');
return h + ':' + m + ':' + s;
//return `${h}:${m}:${s}`;
}
console.log(secondsToTime(7735)); // 02:08:55
/*
secondsToTime(SECONDS) // HH:MM:SS
secondsToTime(8) // 00:00:08
secondsToTime(68) // 00:01:08
secondsToTime(1768) // 00:29:28
secondsToTime(3600) // 01:00:00
secondsToTime(5296) // 01:28:16
secondsToTime(7735) // 02:08:55
secondsToTime(45296) // 12:34:56
secondsToTime(145296) // 40:21:36
secondsToTime(1145296) // 318:08:16
*/
2019 best variant
Format hh:mm:ss
console.log(display(60 * 60 * 2.5 + 25)) // 2.5 hours + 25 seconds
function display (seconds) {
const format = val => `0${Math.floor(val)}`.slice(-2)
const hours = seconds / 3600
const minutes = (seconds % 3600) / 60
return [hours, minutes, seconds % 60].map(format).join(':')
}
You can also use native Date object:
var date = new Date(null);
date.setSeconds(timeInSeconds);
// retrieve time ignoring the browser timezone - returns hh:mm:ss
var utc = date.toUTCString();
// negative start index in substr does not work in IE 8 and earlier
var time = utc.substr(utc.indexOf(':') - 2, 8)
// retrieve each value individually - returns h:m:s
var time = date.getUTCHours() + ':' + date.getUTCMinutes() + ':' + date.getUTCSeconds();
// does not work in IE8 and below - returns hh:mm:ss
var time = date.toISOString().substr(11, 8);
// not recommended - only if seconds number includes timezone difference
var time = date.toTimeString().substr(0, 8);
Of course this solution works only for timeInSeconds less than 24 hours ;)
function secondsToMinutes(time){
return Math.floor(time / 60)+':'+Math.floor(time % 60);
}
To add leading zeros, I would just do:
const secondsToMinSecPadded = time => {
const minutes = "0" + Math.floor(time / 60);
const seconds = "0" + (time - minutes * 60);
return minutes.substr(-2) + ":" + seconds.substr(-2);
};
console.log(secondsToMinSecPadded(241));
Nice and short
Moment.js
If you are using Moment.js then you can use there built in Duration object
const duration = moment.duration(4825, 'seconds');
const h = duration.hours(); // 1
const m = duration.minutes(); // 20
const s = duration.seconds(); // 25
Clean one liner using ES6
const secondsToMinutes = seconds => Math.floor(seconds / 60) + ':' + ('0' + Math.floor(seconds % 60)).slice(-2);
The most concise method I found can be done using in just one line:
let timeString = `${timeInSeconds/60|0}:${timeInSeconds%60}`
Explanation
`${...}`Template literals. Allows for expressions to be converted into a string from within the string itself.Note: Incompatible with IE.
timeInSeconds/60|0Takes the seconds and converts in into minutes (/60). This gives a rational number. From here it is truncated using the bitwise OR (|0)
timeInSeconds%60Remainder (modulo). Gives the remainder of the variable divided by 60.
Hours
This method can be expanded to include hours like this:
let timeString = `${timeInSeconds/60/60|0}:${timeInSeconds/60%60|0}:${timeInSeconds%60}`
Repeating this process, you can even include days.
A one liner (doesnt work with hours):
function sectostr(time) {
return ~~(time / 60) + ":" + (time % 60 < 10 ? "0" : "") + time % 60;
}
Seconds to h:mm:ss
var hours = Math.floor(time / 3600);
time -= hours * 3600;
var minutes = Math.floor(time / 60);
time -= minutes * 60;
var seconds = parseInt(time % 60, 10);
console.log(hours + ':' + (minutes < 10 ? '0' + minutes : minutes) + ':' + (seconds < 10 ? '0' + seconds : seconds));
The Following function will help you to get Days , Hours , Minutes , seconds
toDDHHMMSS(inputSeconds){
const Days = Math.floor( inputSeconds / (60 * 60 * 24) );
const Hour = Math.floor((inputSeconds % (60 * 60 * 24)) / (60 * 60));
const Minutes = Math.floor(((inputSeconds % (60 * 60 * 24)) % (60 * 60)) / 60 );
const Seconds = Math.floor(((inputSeconds % (60 * 60 * 24)) % (60 * 60)) % 60 );
let ddhhmmss = '';
if (Days > 0){
ddhhmmss += Days + ' Day ';
}
if (Hour > 0){
ddhhmmss += Hour + ' Hour ';
}
if (Minutes > 0){
ddhhmmss += Minutes + ' Minutes ';
}
if (Seconds > 0){
ddhhmmss += Seconds + ' Seconds ';
}
return ddhhmmss;
}
alert( toDDHHMMSS(2000));
After all this, yet another simple solution:
const time = new Date(null);
time.setSeconds(7530);
console.log(time.getHours(), time.getMinutes(), time.getSeconds());
Another but much more elegant solution for this is as follows:
/**
* Convert number secs to display time
*
* 65 input becomes 01:05.
*
* #param Number inputSeconds Seconds input.
*/
export const toMMSS = inputSeconds => {
const secs = parseInt( inputSeconds, 10 );
let minutes = Math.floor( secs / 60 );
let seconds = secs - minutes * 60;
if ( 10 > minutes ) {
minutes = '0' + minutes;
}
if ( 10 > seconds ) {
seconds = '0' + seconds;
}
// Return display.
return minutes + ':' + seconds;
};
function formatSeconds(s: number) {
let minutes = ~~(s / 60);
let seconds = ~~(s % 60);
return minutes + ':' + seconds;
}
For adding zeros I really don't see the need to have a full other function where you can simply use for example
var mins=Math.floor(StrTime/60);
var secs=StrTime-mins * 60;
var hrs=Math.floor(StrTime / 3600);
RoundTime.innerHTML=(hrs>9?hrs:"0"+hrs) + ":" + (mins>9?mins:"0"+mins) + ":" + (secs>9?secs:"0"+secs);
Its why we have conditional statements in the first place.
(condition?if true:if false) so if example seconds is more than 9 than just show seconds else add a string 0 before it.
var seconds = 60;
var measuredTime = new Date(null);
measuredTime.setSeconds(seconds); // specify value of SECONDS
var Time = measuredTime.toISOString().substr(11, 8);
document.getElementById("id1").value = Time;
<div class="form-group">
<label for="course" class="col-md-4">Time</label>
<div class="col-md-8">
<input type="text" class="form-control" id="id1" name="field">Min
</div>
</div>
Try this:
Converting Second to HOURS, MIN and SEC.
function convertTime(sec) {
var hours = Math.floor(sec/3600);
(hours >= 1) ? sec = sec - (hours*3600) : hours = '00';
var min = Math.floor(sec/60);
(min >= 1) ? sec = sec - (min*60) : min = '00';
(sec < 1) ? sec='00' : void 0;
(min.toString().length == 1) ? min = '0'+min : void 0;
(sec.toString().length == 1) ? sec = '0'+sec : void 0;
return hours+':'+min+':'+sec;
}
1 - Get rest of division using %. Now you have the seconds that don't complete a minute
2 - Subtract the seconds obtained in step 1 from the total. Now you have the minutes
For example, let's assume you have 700 seconds:
seconds = 700%60); //40 seconds
minutes = (700 - (700%60))/60; //11
//11:40
I was thinking of a faster way to get this done and this is what i came up with
var sec = parseInt(time);
var min=0;
while(sec>59){ sec-=60; min++;}
If we want to convert "time" to minutes and seconds, for example:
// time = 75,3 sec
var sec = parseInt(time); //sec = 75
var min=0;
while(sec>59){ sec-=60; min++;} //sec = 15; min = 1
Put my two cents in :
function convertSecondsToMinutesAndSeconds(seconds){
var minutes;
var seconds;
minutes = Math.floor(seconds/60);
seconds = seconds%60;
return [minutes, seconds];
}
So this :
var minutesAndSeconds = convertSecondsToMinutesAndSeconds(101);
Will have the following output :
[1,41];
Then you can print it like so :
console.log('TIME : ' + minutesSeconds[0] + ' minutes, ' + minutesSeconds[1] + ' seconds');
//TIME : 1 minutes, 41 seconds
export function TrainingTime(props) {
const {train_time } = props;
const hours = Math.floor(train_time/3600);
const minutes = Math.floor((train_time-hours * 3600) / 60);
const seconds = Math.floor((train_time%60));
return `${hours} hrs ${minutes} min ${seconds} sec`;
}
Day.js
If you use day.js, try this.
const dayjs = require('dayjs')
const duration = require('dayjs/plugin/duration')
dayjs.extend(duration)
const time = dayjs.duration(100, 'seconds')
time.seconds() // 40
time.minutes() // 1
time.format('mm:ss') // 01:40
I prefer thinking of Millisecond as its own unit, rather than as a subunit of something else. In that sense, it will have values of 0-999, so you're going to want to Pad three instead of two like I have seen with other answers. Here is an implementation:
function format(n) {
let mil_s = String(n % 1000).padStart(3, '0');
n = Math.trunc(n / 1000);
let sec_s = String(n % 60).padStart(2, '0');
n = Math.trunc(n / 60);
return String(n) + ' m ' + sec_s + ' s ' + mil_s + ' ms';
}
console.log(format(241));
https://developer.mozilla.org/Web/JavaScript/Reference/Global_Objects/String/padStart
Here's an ES6 version of the seconds to minutes and seconds conversion, with padding (00:00 format). It only accepts integer values for seconds and ~~(x) is the shorthand floor operation.
const padTime = n => ("" + n).padStart(2, 0);
const secondsToMinSec = time =>
`${padTime(~~(time / 60))}:${padTime(time - ~~(time / 60) * 60)}`
;
for (let i = 0; i < 10; i++) {
const seconds = ~~(Math.random() * 300);
console.log(seconds, secondsToMinSec(seconds));
}
if you need to work with the result easily later this is what I use:
function seconds2hms(seconds, milliseconds) {
if(milliseconds) {
seconds = Math.floor(seconds/1000);
}
return {h:~~(seconds / 3600),m:~~((seconds % 3600) / 60),s:~~seconds % 60}
}
(used Vishal's code)
strftime.js (strftime github) is one of the best time formatting libraries. It's extremely light - 30KB - and effective. Using it you can convert seconds into time easily in one line of code, relying mostly on the native Date class.
When creating a new Date, each optional argument is positional as follows:
new Date(year, month, day, hours, minutes, seconds, milliseconds);
So if you initialize a new Date with all arguments as zero up to the seconds, you'll get:
var seconds = 150;
var date = new Date(0,0,0,0,0,seconds);
=> Sun Dec 31 1899 00:02:30 GMT-0500 (EST)
You can see that 150 seconds is 2-minutes and 30-seconds, as seen in the date created. Then using an strftime format ("%M:%S" for "MM:SS"), it will output your minutes' string.
var mm_ss_str = strftime("%M:%S", date);
=> "02:30"
In one line, it would look like:
var mm_ss_str = strftime('%M:%S', new Date(0,0,0,0,0,seconds));
=> "02:30"
Plus this would allow you to interchangeable support HH:MM:SS and MM:SS based on the number of seconds. For example:
# Less than an Hour (seconds < 3600)
var seconds = 2435;
strftime((seconds >= 3600 ? '%H:%M:%S' : '%M:%S'), new Date(0,0,0,0,0,seconds));
=> "40:35"
# More than an Hour (seconds >= 3600)
var seconds = 10050;
strftime((seconds >= 3600 ? '%H:%M:%S' : '%M:%S'), new Date(0,0,0,0,0,seconds));
=> "02:47:30"
And of course, you can simply pass whatever format you want to strftime if you want the time string to be more or less semantic.
var format = 'Honey, you said you\'d be read in %S seconds %M minutes ago!';
strftime(format, new Date(0,0,0,0,0,1210));
=> "Honey, you said you'd be read in 10 seconds 20 minutes ago!"
You've done enough code to track minutes and seconds portions of time.
What you could do is add the hours factor in:
var hrd = time % (60 * 60 * 60);
var hours = Math.floor(hrd / 60);
var mind = hrd % 60;
var minutes = Math.floor(mind / 60);
var secd = mind % 60;
var seconds = Math.ceil(secd);
var moreminutes = minutes + hours * 60

How to convert string hours to 'hh:mm:ss' format?

I'm getting my google api response for duration like 1 hour 13 minutes i need to covert this to 'hh:mm:ss' format.How to convert this in React js?
response:
distance: {text: "47.8 km", value: 47790}
duration:
text: "1 hour 13 mins"
value: 4378
__proto__: Object
status: "OK"
It seems the values that are provided: 44790 and 4378, are meters and seconds. Now that you have the seconds as a number you can do all sort of things to get them in the format you want. There are a lot of javascript snippets out there that can do this for you:
function convertHMS(value) {
const sec = parseInt(value, 10); // convert value to number if it's string
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); // get seconds
// add 0 if value < 10
if (hours < 10) {hours = "0"+hours;}
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
return hours+':'+minutes+':'+seconds; // Return is HH : MM : SS
}
const yourTime = convertHMS(4378); // 4378 seconds
// yourTime is 01:12:58
console.log(yourTime);
If you have a basic/beginning Javascript knowledge the only thing that might be funny business in this script are Math.floor() and parseInt().
credits to: https://www.4codev.com/javascript/convert-seconds-to-time-value-hours-minutes-seconds-idpx6943853585885165320.html in this case, you can find these ~10 lines anywhere though, I found them here after a few seconds of searching.
Always try to fix your problem in plain JS first before adding some sort of library that does the work for you, because you don't want to add a complete library for something that can be done in ~10 lines of plain JS. And ofcourse, plain JS works perfectly well in React =).
If you need to support IE6 - IE10 you might want to replace const and let with var (though I do not encourage supporting those browser if you don't have to from a business perspective).
edit: I'm fairly new to answering questions here so I converted the code to a code snippet.
Great solution, Sapulidi. I used your code with a slight modification. Posting for anyone interested.
In typescript
Hours only appear if there are >0 hours
const millisecondsToHHMMSS = (duration: number) => {
const sec = Math.round(duration / 1000);
const hours = Math.floor(sec / 3600); // get hours
const minutes = Math.floor((sec - hours * 3600) / 60); // get minutes
const seconds = sec - hours * 3600 - minutes * 60; // get seconds
// add 0 if value < 10
let sHours = hours > 0 ? `${hours}:` : '';
let sMinutes = `${minutes}`;
let sSeconds = `${seconds}`;
if (minutes < 10) {
sMinutes = '0' + sMinutes;
}
if (seconds < 10) {
sSeconds = '0' + sSeconds;
}
return sHours + sMinutes + ':' + sSeconds;
// Return is HH:MM:SS
};
let timeWithHours = 12345
let formattedWithHours = millisecondsToHHMMSS(timeWithHours)
let timeWithoutHours = 12345678
let formattedWithoutHours = millisecondsToHHMMSS(timeWithoutHours)
console.log(formattedWithHours)
console.log(formattedWithoutHours)
It is not related to React. You can simply use moment.js
moment(distance.value).format('hh:mm:ss');
You could either use one of the date formatting libraries (e.g. momentjs or date-fns) or just calculate it by yourself. You are getting the duration in seconds (it seems to be 4378 seconds), so calculating it by yourself won't be much of an effort.
Here is an example:
const values = getHoursMinutesAndSeconds(4378);
console.log(values);
console.log(`${zeroPadding(values.hours, 2)}:${zeroPadding(values.minutes, 2)}:${zeroPadding(values.seconds, 2)}`);
function getHoursMinutesAndSeconds (totalSeconds) {
// step 1: create seconds and hoursAndMinutes (minutes, but might be larger than 60)
const hoursAndMinutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
// step 2: create minutes and hours from hoursAndMinutes
const hours = Math.floor(hoursAndMinutes / 60);
const minutes = hoursAndMinutes % 60;
return { hours, minutes, seconds };
}
function zeroPadding (number, length) {
return String(number).padStart(length, '0');
}

How to format time in JavaScript, without a framework [duplicate]

This is a common problem but I'm not sure how to solve it. The code below works fine.
var mind = time % (60 * 60);
var minutes = Math.floor(mind / 60);
var secd = mind % 60;
var seconds = Math.ceil(secd);
However, when I get to 1 hour or 3600 seconds it returns 0 minutes and 0 seconds. How can I avoid this so it returns all the minutes?
To get the number of full minutes, divide the number of total seconds by 60 (60 seconds/minute):
const minutes = Math.floor(time / 60);
And to get the remaining seconds, multiply the full minutes with 60 and subtract from the total seconds:
const seconds = time - minutes * 60;
Now if you also want to get the full hours too, divide the number of total seconds by 3600 (60 minutes/hour · 60 seconds/minute) first, then calculate the remaining seconds:
const hours = Math.floor(time / 3600);
time = time - hours * 3600;
Then you calculate the full minutes and remaining seconds.
Bonus:
Use the following code to pretty-print the time (suggested by Dru):
function str_pad_left(string, pad, length) {
return (new Array(length + 1).join(pad) + string).slice(-length);
}
const finalTime = str_pad_left(minutes, '0', 2) + ':' + str_pad_left(seconds, '0', 2);
Another fancy solution:
function fancyTimeFormat(duration) {
// Hours, minutes and seconds
const hrs = ~~(duration / 3600);
const mins = ~~((duration % 3600) / 60);
const secs = ~~duration % 60;
// Output like "1:01" or "4:03:59" or "123:03:59"
let ret = "";
if (hrs > 0) {
ret += "" + hrs + ":" + (mins < 10 ? "0" : "");
}
ret += "" + mins + ":" + (secs < 10 ? "0" : "");
ret += "" + secs;
return ret;
}
console.log(
fancyTimeFormat(1),
fancyTimeFormat(10),
fancyTimeFormat(100),
fancyTimeFormat(1000),
fancyTimeFormat(10000),
);
~~ is a shorthand for Math.floor, see this link for more info
For people dropping in hoping for a quick simple and thus short solution to format seconds into M:SS :
function fmtMSS(s){return(s-(s%=60))/60+(9<s?':':':0')+s}
done..
The function accepts either a Number (preferred) or a String (2 conversion 'penalties' which you can halve by prepending + in the function call's argument for s as in: fmtMSS(+strSeconds)), representing positive integer seconds s as argument.
Examples:
fmtMSS( 0 ); // 0:00
fmtMSS( '8'); // 0:08
fmtMSS( 9 ); // 0:09
fmtMSS( '10'); // 0:10
fmtMSS( 59 ); // 0:59
fmtMSS( +'60'); // 1:00
fmtMSS( 69 ); // 1:09
fmtMSS( 3599 ); // 59:59
fmtMSS('3600'); // 60:00
fmtMSS('3661'); // 61:01
fmtMSS( 7425 ); // 123:45
Breakdown:
function fmtMSS(s){ // accepts seconds as Number or String. Returns m:ss
return( s - // take value s and subtract (will try to convert String to Number)
( s %= 60 ) // the new value of s, now holding the remainder of s divided by 60
// (will also try to convert String to Number)
) / 60 + ( // and divide the resulting Number by 60
// (can never result in a fractional value = no need for rounding)
// to which we concatenate a String (converts the Number to String)
// who's reference is chosen by the conditional operator:
9 < s // if seconds is larger than 9
? ':' // then we don't need to prepend a zero
: ':0' // else we do need to prepend a zero
) + s ; // and we add Number s to the string (converting it to String as well)
}
Note: Negative range could be added by prepending (0>s?(s=-s,'-'):'')+ to the return expression (actually, (0>s?(s=-s,'-'):0)+ would work as well).
2020 UPDATE
Using basic math and simple javascript this can be done in just a few lines of code.
EXAMPLE - Convert 7735 seconds to HH:MM:SS.
MATH:
Calculations use:
Math.floor() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor
The Math.floor() function returns the largest integer less than or equal to a given number.
% arithmetic operator (Remainder) - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Remainder
The remainder operator returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend.
Check out code below. Seconds are divided by 3600 to get number of hours and a remainder, which is used to calculate number of minutes and seconds.
HOURS => 7735 / 3600 = 2 remainder 535
MINUTES => 535 / 60 = 8 remainder 55
SECONDS => 55
LEADING ZEROS:
Many answers here use complicated methods to show number of hours, minutes and seconds in a proper way with leading zero - 45, 04 etc. This can be done using padStart(). This works for strings so the number must be converted to string using toString().
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
The padStart() method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of the current string.
CODE:
function secondsToTime(e){
const h = Math.floor(e / 3600).toString().padStart(2,'0'),
m = Math.floor(e % 3600 / 60).toString().padStart(2,'0'),
s = Math.floor(e % 60).toString().padStart(2,'0');
return h + ':' + m + ':' + s;
//return `${h}:${m}:${s}`;
}
console.log(secondsToTime(7735)); // 02:08:55
/*
secondsToTime(SECONDS) // HH:MM:SS
secondsToTime(8) // 00:00:08
secondsToTime(68) // 00:01:08
secondsToTime(1768) // 00:29:28
secondsToTime(3600) // 01:00:00
secondsToTime(5296) // 01:28:16
secondsToTime(7735) // 02:08:55
secondsToTime(45296) // 12:34:56
secondsToTime(145296) // 40:21:36
secondsToTime(1145296) // 318:08:16
*/
2019 best variant
Format hh:mm:ss
console.log(display(60 * 60 * 2.5 + 25)) // 2.5 hours + 25 seconds
function display (seconds) {
const format = val => `0${Math.floor(val)}`.slice(-2)
const hours = seconds / 3600
const minutes = (seconds % 3600) / 60
return [hours, minutes, seconds % 60].map(format).join(':')
}
You can also use native Date object:
var date = new Date(null);
date.setSeconds(timeInSeconds);
// retrieve time ignoring the browser timezone - returns hh:mm:ss
var utc = date.toUTCString();
// negative start index in substr does not work in IE 8 and earlier
var time = utc.substr(utc.indexOf(':') - 2, 8)
// retrieve each value individually - returns h:m:s
var time = date.getUTCHours() + ':' + date.getUTCMinutes() + ':' + date.getUTCSeconds();
// does not work in IE8 and below - returns hh:mm:ss
var time = date.toISOString().substr(11, 8);
// not recommended - only if seconds number includes timezone difference
var time = date.toTimeString().substr(0, 8);
Of course this solution works only for timeInSeconds less than 24 hours ;)
function secondsToMinutes(time){
return Math.floor(time / 60)+':'+Math.floor(time % 60);
}
To add leading zeros, I would just do:
const secondsToMinSecPadded = time => {
const minutes = "0" + Math.floor(time / 60);
const seconds = "0" + (time - minutes * 60);
return minutes.substr(-2) + ":" + seconds.substr(-2);
};
console.log(secondsToMinSecPadded(241));
Nice and short
Moment.js
If you are using Moment.js then you can use there built in Duration object
const duration = moment.duration(4825, 'seconds');
const h = duration.hours(); // 1
const m = duration.minutes(); // 20
const s = duration.seconds(); // 25
Clean one liner using ES6
const secondsToMinutes = seconds => Math.floor(seconds / 60) + ':' + ('0' + Math.floor(seconds % 60)).slice(-2);
The most concise method I found can be done using in just one line:
let timeString = `${timeInSeconds/60|0}:${timeInSeconds%60}`
Explanation
`${...}`Template literals. Allows for expressions to be converted into a string from within the string itself.Note: Incompatible with IE.
timeInSeconds/60|0Takes the seconds and converts in into minutes (/60). This gives a rational number. From here it is truncated using the bitwise OR (|0)
timeInSeconds%60Remainder (modulo). Gives the remainder of the variable divided by 60.
Hours
This method can be expanded to include hours like this:
let timeString = `${timeInSeconds/60/60|0}:${timeInSeconds/60%60|0}:${timeInSeconds%60}`
Repeating this process, you can even include days.
A one liner (doesnt work with hours):
function sectostr(time) {
return ~~(time / 60) + ":" + (time % 60 < 10 ? "0" : "") + time % 60;
}
Seconds to h:mm:ss
var hours = Math.floor(time / 3600);
time -= hours * 3600;
var minutes = Math.floor(time / 60);
time -= minutes * 60;
var seconds = parseInt(time % 60, 10);
console.log(hours + ':' + (minutes < 10 ? '0' + minutes : minutes) + ':' + (seconds < 10 ? '0' + seconds : seconds));
The Following function will help you to get Days , Hours , Minutes , seconds
toDDHHMMSS(inputSeconds){
const Days = Math.floor( inputSeconds / (60 * 60 * 24) );
const Hour = Math.floor((inputSeconds % (60 * 60 * 24)) / (60 * 60));
const Minutes = Math.floor(((inputSeconds % (60 * 60 * 24)) % (60 * 60)) / 60 );
const Seconds = Math.floor(((inputSeconds % (60 * 60 * 24)) % (60 * 60)) % 60 );
let ddhhmmss = '';
if (Days > 0){
ddhhmmss += Days + ' Day ';
}
if (Hour > 0){
ddhhmmss += Hour + ' Hour ';
}
if (Minutes > 0){
ddhhmmss += Minutes + ' Minutes ';
}
if (Seconds > 0){
ddhhmmss += Seconds + ' Seconds ';
}
return ddhhmmss;
}
alert( toDDHHMMSS(2000));
After all this, yet another simple solution:
const time = new Date(null);
time.setSeconds(7530);
console.log(time.getHours(), time.getMinutes(), time.getSeconds());
Another but much more elegant solution for this is as follows:
/**
* Convert number secs to display time
*
* 65 input becomes 01:05.
*
* #param Number inputSeconds Seconds input.
*/
export const toMMSS = inputSeconds => {
const secs = parseInt( inputSeconds, 10 );
let minutes = Math.floor( secs / 60 );
let seconds = secs - minutes * 60;
if ( 10 > minutes ) {
minutes = '0' + minutes;
}
if ( 10 > seconds ) {
seconds = '0' + seconds;
}
// Return display.
return minutes + ':' + seconds;
};
function formatSeconds(s: number) {
let minutes = ~~(s / 60);
let seconds = ~~(s % 60);
return minutes + ':' + seconds;
}
For adding zeros I really don't see the need to have a full other function where you can simply use for example
var mins=Math.floor(StrTime/60);
var secs=StrTime-mins * 60;
var hrs=Math.floor(StrTime / 3600);
RoundTime.innerHTML=(hrs>9?hrs:"0"+hrs) + ":" + (mins>9?mins:"0"+mins) + ":" + (secs>9?secs:"0"+secs);
Its why we have conditional statements in the first place.
(condition?if true:if false) so if example seconds is more than 9 than just show seconds else add a string 0 before it.
var seconds = 60;
var measuredTime = new Date(null);
measuredTime.setSeconds(seconds); // specify value of SECONDS
var Time = measuredTime.toISOString().substr(11, 8);
document.getElementById("id1").value = Time;
<div class="form-group">
<label for="course" class="col-md-4">Time</label>
<div class="col-md-8">
<input type="text" class="form-control" id="id1" name="field">Min
</div>
</div>
Try this:
Converting Second to HOURS, MIN and SEC.
function convertTime(sec) {
var hours = Math.floor(sec/3600);
(hours >= 1) ? sec = sec - (hours*3600) : hours = '00';
var min = Math.floor(sec/60);
(min >= 1) ? sec = sec - (min*60) : min = '00';
(sec < 1) ? sec='00' : void 0;
(min.toString().length == 1) ? min = '0'+min : void 0;
(sec.toString().length == 1) ? sec = '0'+sec : void 0;
return hours+':'+min+':'+sec;
}
1 - Get rest of division using %. Now you have the seconds that don't complete a minute
2 - Subtract the seconds obtained in step 1 from the total. Now you have the minutes
For example, let's assume you have 700 seconds:
seconds = 700%60); //40 seconds
minutes = (700 - (700%60))/60; //11
//11:40
I was thinking of a faster way to get this done and this is what i came up with
var sec = parseInt(time);
var min=0;
while(sec>59){ sec-=60; min++;}
If we want to convert "time" to minutes and seconds, for example:
// time = 75,3 sec
var sec = parseInt(time); //sec = 75
var min=0;
while(sec>59){ sec-=60; min++;} //sec = 15; min = 1
Put my two cents in :
function convertSecondsToMinutesAndSeconds(seconds){
var minutes;
var seconds;
minutes = Math.floor(seconds/60);
seconds = seconds%60;
return [minutes, seconds];
}
So this :
var minutesAndSeconds = convertSecondsToMinutesAndSeconds(101);
Will have the following output :
[1,41];
Then you can print it like so :
console.log('TIME : ' + minutesSeconds[0] + ' minutes, ' + minutesSeconds[1] + ' seconds');
//TIME : 1 minutes, 41 seconds
export function TrainingTime(props) {
const {train_time } = props;
const hours = Math.floor(train_time/3600);
const minutes = Math.floor((train_time-hours * 3600) / 60);
const seconds = Math.floor((train_time%60));
return `${hours} hrs ${minutes} min ${seconds} sec`;
}
Day.js
If you use day.js, try this.
const dayjs = require('dayjs')
const duration = require('dayjs/plugin/duration')
dayjs.extend(duration)
const time = dayjs.duration(100, 'seconds')
time.seconds() // 40
time.minutes() // 1
time.format('mm:ss') // 01:40
I prefer thinking of Millisecond as its own unit, rather than as a subunit of something else. In that sense, it will have values of 0-999, so you're going to want to Pad three instead of two like I have seen with other answers. Here is an implementation:
function format(n) {
let mil_s = String(n % 1000).padStart(3, '0');
n = Math.trunc(n / 1000);
let sec_s = String(n % 60).padStart(2, '0');
n = Math.trunc(n / 60);
return String(n) + ' m ' + sec_s + ' s ' + mil_s + ' ms';
}
console.log(format(241));
https://developer.mozilla.org/Web/JavaScript/Reference/Global_Objects/String/padStart
Here's an ES6 version of the seconds to minutes and seconds conversion, with padding (00:00 format). It only accepts integer values for seconds and ~~(x) is the shorthand floor operation.
const padTime = n => ("" + n).padStart(2, 0);
const secondsToMinSec = time =>
`${padTime(~~(time / 60))}:${padTime(time - ~~(time / 60) * 60)}`
;
for (let i = 0; i < 10; i++) {
const seconds = ~~(Math.random() * 300);
console.log(seconds, secondsToMinSec(seconds));
}
if you need to work with the result easily later this is what I use:
function seconds2hms(seconds, milliseconds) {
if(milliseconds) {
seconds = Math.floor(seconds/1000);
}
return {h:~~(seconds / 3600),m:~~((seconds % 3600) / 60),s:~~seconds % 60}
}
(used Vishal's code)
strftime.js (strftime github) is one of the best time formatting libraries. It's extremely light - 30KB - and effective. Using it you can convert seconds into time easily in one line of code, relying mostly on the native Date class.
When creating a new Date, each optional argument is positional as follows:
new Date(year, month, day, hours, minutes, seconds, milliseconds);
So if you initialize a new Date with all arguments as zero up to the seconds, you'll get:
var seconds = 150;
var date = new Date(0,0,0,0,0,seconds);
=> Sun Dec 31 1899 00:02:30 GMT-0500 (EST)
You can see that 150 seconds is 2-minutes and 30-seconds, as seen in the date created. Then using an strftime format ("%M:%S" for "MM:SS"), it will output your minutes' string.
var mm_ss_str = strftime("%M:%S", date);
=> "02:30"
In one line, it would look like:
var mm_ss_str = strftime('%M:%S', new Date(0,0,0,0,0,seconds));
=> "02:30"
Plus this would allow you to interchangeable support HH:MM:SS and MM:SS based on the number of seconds. For example:
# Less than an Hour (seconds < 3600)
var seconds = 2435;
strftime((seconds >= 3600 ? '%H:%M:%S' : '%M:%S'), new Date(0,0,0,0,0,seconds));
=> "40:35"
# More than an Hour (seconds >= 3600)
var seconds = 10050;
strftime((seconds >= 3600 ? '%H:%M:%S' : '%M:%S'), new Date(0,0,0,0,0,seconds));
=> "02:47:30"
And of course, you can simply pass whatever format you want to strftime if you want the time string to be more or less semantic.
var format = 'Honey, you said you\'d be read in %S seconds %M minutes ago!';
strftime(format, new Date(0,0,0,0,0,1210));
=> "Honey, you said you'd be read in 10 seconds 20 minutes ago!"
You've done enough code to track minutes and seconds portions of time.
What you could do is add the hours factor in:
var hrd = time % (60 * 60 * 60);
var hours = Math.floor(hrd / 60);
var mind = hrd % 60;
var minutes = Math.floor(mind / 60);
var secd = mind % 60;
var seconds = Math.ceil(secd);
var moreminutes = minutes + hours * 60

How to convert time in milliseconds to hours, min, sec format in JavaScript?

I have a time as a number of milliseconds and I want to convert it to a HH:MM:SS format. It should wrap around, with milliseconds = 86400000 I want to get 00:00:00.
How about creating a function like this:
function msToTime(duration) {
var milliseconds = Math.floor((duration % 1000) / 100),
seconds = Math.floor((duration / 1000) % 60),
minutes = Math.floor((duration / (1000 * 60)) % 60),
hours = Math.floor((duration / (1000 * 60 * 60)) % 24);
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
}
console.log(msToTime(300000))
To Convert time in millisecond to human readable format.
function msToTime(ms) {
let seconds = (ms / 1000).toFixed(1);
let minutes = (ms / (1000 * 60)).toFixed(1);
let hours = (ms / (1000 * 60 * 60)).toFixed(1);
let days = (ms / (1000 * 60 * 60 * 24)).toFixed(1);
if (seconds < 60) return seconds + " Sec";
else if (minutes < 60) return minutes + " Min";
else if (hours < 24) return hours + " Hrs";
else return days + " Days"
}
console.log(msToTime(1000))
console.log(msToTime(10000))
console.log(msToTime(300000))
console.log(msToTime(3600000))
console.log(msToTime(86400000))
I had the same problem, this is what I ended up doing:
function parseMillisecondsIntoReadableTime(milliseconds){
//Get hours from milliseconds
var hours = milliseconds / (1000*60*60);
var absoluteHours = Math.floor(hours);
var h = absoluteHours > 9 ? absoluteHours : '0' + absoluteHours;
//Get remainder from hours and convert to minutes
var minutes = (hours - absoluteHours) * 60;
var absoluteMinutes = Math.floor(minutes);
var m = absoluteMinutes > 9 ? absoluteMinutes : '0' + absoluteMinutes;
//Get remainder from minutes and convert to seconds
var seconds = (minutes - absoluteMinutes) * 60;
var absoluteSeconds = Math.floor(seconds);
var s = absoluteSeconds > 9 ? absoluteSeconds : '0' + absoluteSeconds;
return h + ':' + m + ':' + s;
}
var time = parseMillisecondsIntoReadableTime(86400000);
alert(time);
Here is my solution
let h,m,s;
h = Math.floor(timeInMiliseconds/1000/60/60);
m = Math.floor((timeInMiliseconds/1000/60/60 - h)*60);
s = Math.floor(((timeInMiliseconds/1000/60/60 - h)*60 - m)*60);
// to get time format 00:00:00
s < 10 ? s = `0${s}`: s = `${s}`
m < 10 ? m = `0${m}`: m = `${m}`
h < 10 ? h = `0${h}`: h = `${h}`
console.log(`${s}:${m}:${h}`);
This one returns time like youtube videos
function getYoutubeLikeToDisplay(millisec) {
var seconds = (millisec / 1000).toFixed(0);
var minutes = Math.floor(seconds / 60);
var hours = "";
if (minutes > 59) {
hours = Math.floor(minutes / 60);
hours = (hours >= 10) ? hours : "0" + hours;
minutes = minutes - (hours * 60);
minutes = (minutes >= 10) ? minutes : "0" + minutes;
}
seconds = Math.floor(seconds % 60);
seconds = (seconds >= 10) ? seconds : "0" + seconds;
if (hours != "") {
return hours + ":" + minutes + ":" + seconds;
}
return minutes + ":" + seconds;
}
Output:
getYoutubeLikeToDisplay(129900) = "2:10"
getYoutubeLikeToDisplay(1229900) = "20:30"
getYoutubeLikeToDisplay(21229900) = "05:53:50"
Sorry, late to the party. The accepted answer did not cut it for me, so I wrote it myself.
Output:
2h 59s
1h 59m
1h
1h 59s
59m 59s
59s
Code (Typescript):
function timeConversion(duration: number) {
const portions: string[] = [];
const msInHour = 1000 * 60 * 60;
const hours = Math.trunc(duration / msInHour);
if (hours > 0) {
portions.push(hours + 'h');
duration = duration - (hours * msInHour);
}
const msInMinute = 1000 * 60;
const minutes = Math.trunc(duration / msInMinute);
if (minutes > 0) {
portions.push(minutes + 'm');
duration = duration - (minutes * msInMinute);
}
const seconds = Math.trunc(duration / 1000);
if (seconds > 0) {
portions.push(seconds + 's');
}
return portions.join(' ');
}
console.log(timeConversion((60 * 60 * 1000) + (59 * 60 * 1000) + (59 * 1000)));
console.log(timeConversion((60 * 60 * 1000) + (59 * 60 * 1000) ));
console.log(timeConversion((60 * 60 * 1000) ));
console.log(timeConversion((60 * 60 * 1000) + (59 * 1000)));
console.log(timeConversion( (59 * 60 * 1000) + (59 * 1000)));
console.log(timeConversion( (59 * 1000)));
The above snippets don't work for cases with more than 1 day (They are simply ignored).
For this you can use:
function convertMS(ms) {
var d, h, m, s;
s = Math.floor(ms / 1000);
m = Math.floor(s / 60);
s = s % 60;
h = Math.floor(m / 60);
m = m % 60;
d = Math.floor(h / 24);
h = h % 24;
h += d * 24;
return h + ':' + m + ':' + s;
}
Thanks to https://gist.github.com/remino/1563878
I needed time only up to one day, 24h, this was my take:
const milliseconds = 5680000;
const hours = `0${new Date(milliseconds).getHours() - 1}`.slice(-2);
const minutes = `0${new Date(milliseconds).getMinutes()}`.slice(-2);
const seconds = `0${new Date(milliseconds).getSeconds()}`.slice(-2);
const time = `${hours}:${minutes}:${seconds}`
console.log(time);
you could get days this way as well if needed.
Format as hh:mm:ss with optional padding
(1:59:59 or 01:59:59)
(1:59 or 01:59)
(Default: no padding)
Based loosely on Chand's answer.
function formatMilliseconds(milliseconds, padStart) {
function pad(num) {
return `${num}`.padStart(2, '0');
}
let asSeconds = milliseconds / 1000;
let hours = undefined;
let minutes = Math.floor(asSeconds / 60);
let seconds = Math.floor(asSeconds % 60);
if (minutes > 59) {
hours = Math.floor(minutes / 60);
minutes %= 60;
}
return hours
? `${padStart ? pad(hours) : hours}:${pad(minutes)}:${pad(seconds)}`
: `${padStart ? pad(minutes) : minutes}:${pad(seconds)}`;
}
Tests:
let s = 1000;
let m = 60*s;
let h = 60*m;
console.log(formatMilliseconds(1*h)); // 1:00:00
console.log(formatMilliseconds(1*h, true)); // 01:00:00
console.log(formatMilliseconds(59*m + 59*s)); // 59:59
console.log(formatMilliseconds(59*m + 59*s, true)); // 59:59
console.log(formatMilliseconds(9*m + 9*s)); // 9:09
console.log(formatMilliseconds(9*m + 9*s, true)); // 09:09
console.log(formatMilliseconds(5*s)); // 0:05
console.log(formatMilliseconds(5*s, true)); // 00:05
console.log(formatMilliseconds(2400*s)); // 40:00
console.log(formatMilliseconds(2400*s, true)); // 40:00
.
.
.
If you need millisecond precision, you can get the fractional part using the following:
(asSeconds % 1).toFixed(3).substring(1)
Your returns would end up looking like this (break it up for readability as necessary):
`${padStart ? pad(hours) : hours}:${pad(minutes)}:${pad(seconds)}${(asSeconds % 1).toFixed(3).substring(1)}`
There are probably better ways to do that, but this naive solution gets the job done.
Test:
let asSeconds = 59.5219;
let seconds = Math.floor(asSeconds);
console.log(`${pad(seconds)}${(asSeconds % 1).toFixed(3).substring(1)}`);
// Equivalent to above, without using `pad()`:
//console.log(`${String(seconds).padStart(2, '0')}${(asSeconds % 1).toFixed(3).substring(1)}`);
// Output: 59.522
// The following is written in Typescript, should be easy to translate to JS
function humanReadableDuration(msDuration: int): string {
const h = Math.floor(msDuration / 1000 / 60 / 60);
const m = Math.floor((msDuration / 1000 / 60 / 60 - h) * 60);
const s = Math.floor(((msDuration / 1000 / 60 / 60 - h) * 60 - m) * 60);
// To get time format 00:00:00
const seconds: string = s < 10 ? `0${s}` : `${s}`;
const minutes: string = m < 10 ? `0${m}` : `${m}`;
const hours: string = h < 10 ? `0${h}` : `${h}`;
return `${hours}h ${minutes}m ${seconds}s`;
}
This solution uses one function to split milliseconds into a parts object, and another function to format the parts object.
I created 2 format functions, one as you requested, and another that prints a friendly string and considering singular/plural, and includes an option to show milliseconds.
function parseDuration(duration) {
let remain = duration
let days = Math.floor(remain / (1000 * 60 * 60 * 24))
remain = remain % (1000 * 60 * 60 * 24)
let hours = Math.floor(remain / (1000 * 60 * 60))
remain = remain % (1000 * 60 * 60)
let minutes = Math.floor(remain / (1000 * 60))
remain = remain % (1000 * 60)
let seconds = Math.floor(remain / (1000))
remain = remain % (1000)
let milliseconds = remain
return {
days,
hours,
minutes,
seconds,
milliseconds
};
}
function formatTime(o, useMilli = false) {
let parts = []
if (o.days) {
let ret = o.days + ' day'
if (o.days !== 1) {
ret += 's'
}
parts.push(ret)
}
if (o.hours) {
let ret = o.hours + ' hour'
if (o.hours !== 1) {
ret += 's'
}
parts.push(ret)
}
if (o.minutes) {
let ret = o.minutes + ' minute'
if (o.minutes !== 1) {
ret += 's'
}
parts.push(ret)
}
if (o.seconds) {
let ret = o.seconds + ' second'
if (o.seconds !== 1) {
ret += 's'
}
parts.push(ret)
}
if (useMilli && o.milliseconds) {
let ret = o.milliseconds + ' millisecond'
if (o.milliseconds !== 1) {
ret += 's'
}
parts.push(ret)
}
if (parts.length === 0) {
return 'instantly'
} else {
return parts.join(' ')
}
}
function formatTimeHMS(o) {
let hours = o.hours.toString()
if (hours.length === 1) hours = '0' + hours
let minutes = o.minutes.toString()
if (minutes.length === 1) minutes = '0' + minutes
let seconds = o.seconds.toString()
if (seconds.length === 1) seconds = '0' + seconds
return hours + ":" + minutes + ":" + seconds
}
function formatDurationHMS(duration) {
let time = parseDuration(duration)
return formatTimeHMS(time)
}
function formatDuration(duration, useMilli = false) {
let time = parseDuration(duration)
return formatTime(time, useMilli)
}
console.log(formatDurationHMS(57742343234))
console.log(formatDuration(57742343234))
console.log(formatDuration(5423401000))
console.log(formatDuration(500))
console.log(formatDuration(500, true))
console.log(formatDuration(1000 * 30))
console.log(formatDuration(1000 * 60 * 30))
console.log(formatDuration(1000 * 60 * 60 * 12))
console.log(formatDuration(1000 * 60 * 60 * 1))
Worked for me
msToTime(milliseconds) {
//Get hours from milliseconds
var hours = milliseconds / (1000*60*60);
var absoluteHours = Math.floor(hours);
var h = absoluteHours > 9 ? absoluteHours : '0' + absoluteHours;
//Get remainder from hours and convert to minutes
var minutes = (hours - absoluteHours) * 60;
var absoluteMinutes = Math.floor(minutes);
var m = absoluteMinutes > 9 ? absoluteMinutes : '0' + absoluteMinutes;
//Get remainder from minutes and convert to seconds
var seconds = (minutes - absoluteMinutes) * 60;
var absoluteSeconds = Math.floor(seconds);
var s = absoluteSeconds > 9 ? absoluteSeconds : '0' + absoluteSeconds;
return h == "00" ? m + ':' + s : h + ':' + m + ':' + s;
}
Human-readable code for human-readable output and you can extend this to light years or nanoseconds or what have you very intuitively. Obviously you'd want to convert this to a function and re-use some of those intermediate modulo calls.
second = 1000
minute = second * 60
hour = minute * 60
day = hour * 24
test = 3 * day + 2 * hour + 11 * minute + 58 * second
console.log(Math.floor(test / day))
console.log(Math.floor(test % day / hour))
console.log(Math.floor(test % day % hour / minute))
console.log(Math.floor(test % day % hour % minute / second))
Extending on #Rick's answer, I prefer something like this:
function msToReadableTime(time){
const second = 1000;
const minute = second * 60;
const hour = minute * 60;
let hours = Math.floor(time / hour % 24);
let minutes = Math.floor(time / minute % 60);
let seconds = Math.floor(time / second % 60);
return hours + ':' + minutes + ":" + seconds;
}
Based on #Chand answer. This is the implementation in Typescript. A bit safer than coercing types in JS. If you remove the type annotation should be valid JS. Also using new string functions to normalise the time.
function displayTime(millisec: number) {
const normalizeTime = (time: string): string => (time.length === 1) ? time.padStart(2, '0') : time;
let seconds: string = (millisec / 1000).toFixed(0);
let minutes: string = Math.floor(parseInt(seconds) / 60).toString();
let hours: string = '';
if (parseInt(minutes) > 59) {
hours = normalizeTime(Math.floor(parseInt(minutes) / 60).toString());
minutes = normalizeTime((parseInt(minutes) - (parseInt(hours) * 60)).toString());
}
seconds = normalizeTime(Math.floor(parseInt(seconds) % 60).toString());
if (hours !== '') {
return `${hours}:${minutes}:${seconds}`;
}
return `${minutes}:${seconds}`;
}
I recently ran into this situation. My focus was on clean readability and reusability.
Use
(See function definition below)
timeUnits(86400000) // {days: 1, hours: 0, minutes: 0, seconds: 0, ms: 0}
Then you can use the data to do whatever you want (like build a string).
Other examples:
timeUnits(214870123) // {days: 2, hours: 11, minutes: 41, seconds: 10, ms: 123}
timeUnits('70123') // null
Function
/**
* Converts milliseconds into greater time units as possible
* #param {int} ms - Amount of time measured in milliseconds
* #return {?Object} Reallocated time units. NULL on failure.
*/
function timeUnits( ms ) {
if ( !Number.isInteger(ms) ) {
return null
}
/**
* Takes as many whole units from the time pool (ms) as possible
* #param {int} msUnit - Size of a single unit in milliseconds
* #return {int} Number of units taken from the time pool
*/
const allocate = msUnit => {
const units = Math.trunc(ms / msUnit)
ms -= units * msUnit
return units
}
// Property order is important here.
// These arguments are the respective units in ms.
return {
// weeks: allocate(604800000), // Uncomment for weeks
days: allocate(86400000),
hours: allocate(3600000),
minutes: allocate(60000),
seconds: allocate(1000),
ms: ms // remainder
}
}
It's written in such a way so that you can easily implement other units (for example, where I commented out implementation for weeks) so long as you know their worth in milliseconds.
my solution
var sunriseMills = 1517573074000; // sunrise in NewYork on Feb 3, 2018 - UTC time
var offsetCityMills = -5 * 3600 * 1000; // NewYork delay to UTC
var offsetDeviceMills = new Date().getTimezoneOffset() * 60 * 1000 ; // eg. I live in Romania (UTC+2) >> getTimezoneOffset() = 120
var textTime = new Date(sunriseMills + offsetCityMills + offsetDeviceMills)
.toLocaleTimeString('en-US', { hour: 'numeric', minute: 'numeric' });
textTime will become '7.04 AM'
A Date object can be constructed from milliseconds:
const date = new Date(0, 0, 0, 0, 0, 0, milliseconds);
In your question you say milliseconds seconds should 'wrap around' at 86400000. Since we know there are 86400000 milliseconds in a day, we can simply take the time from the date object, and ignore every other part of the date as irrelevant.
The time can then be obtained in any number of formats. The one you require matches that used in the United Kingdom, locale en-GB:
const hms = d.toLocaleTimeString('en-GB');
If you're using typescript, this could be a good thing for you
enum ETime {
Seconds = 1000,
Minutes = 60000,
Hours = 3600000,
SecInMin = 60,
MinInHours = 60,
HoursMod = 24,
timeMin = 10,
}
interface ITime {
millis: number
modulo: number
}
const Times = {
seconds: {
millis: ETime.Seconds,
modulo: ETime.SecInMin,
},
minutes: {
millis: ETime.Minutes,
modulo: ETime.MinInHours,
},
hours: {
millis: ETime.Hours,
modulo: ETime.HoursMod,
},
}
const dots: string = ":"
const msToTime = (duration: number, needHours: boolean = true): string => {
const getCorrectTime = (divider: ITime): string => {
const timeStr: number = Math.floor(
(duration / divider.millis) % divider.modulo,
)
return timeStr < ETime.timeMin ? "0" + timeStr : String(timeStr)
}
return (
(needHours ? getCorrectTime(Times.hours) + dots : "") +
getCorrectTime(Times.minutes) +
dots +
getCorrectTime(Times.seconds)
)
}
In my implementation I used Moment.js:
export default (value) =>
const duration = moment.duration(value);
const milliseconds = duration.milliseconds();
const seconds = duration.seconds();
const minutes = duration.minutes();
const hours = duration.hours();
const day = duration.days();
const sDay = `${day}d `;
const sHours = (hours < 10) ? `0${hours}h ` : `${hours}h `;
const sMinutes = (minutes < 10) ? `0${minutes}' ` : `${minutes}' `;
const sSeconds = (seconds < 10) ? `0${seconds}" ` : `${seconds}" `;
const sMilliseconds = `${milliseconds}ms`;
...
}
Once got the strings, I composed them as I want.
I works for me as i get milliseconds=1592380675409 using javascript method getTime() which returns the number of milliseconds between midnight of January 1, 1970 and the specified date.
var d = new Date();//Wed Jun 17 2020 13:27:55 GMT+0530 (India Standard Time)
var n = d.getTime();//1592380675409 this value is store somewhere
//function call
console.log(convertMillisecToHrMinSec(1592380675409));
var convertMillisecToHrMinSec = (time) => {
let date = new Date(time);
let hr = date.getHours();
let min = date.getMinutes();
let sec = date.getSeconds();
hr = (hr < 10) ? "0"+ hr : hr;
min = (min < 10) ? "0"+ min : min;
sec = (sec < 10) ? "0"+ sec : sec;
return hr + ':' + min + ":" + sec;//01:27:55
}
A refactor from #dusht to ES6+ and more functional:
const addPrefix = time => time < 10 ? '0' + time : time;
const toHours = time => addPrefix(Math.floor((time / (1000 * 60 * 60)) % 24));
const toMinutes = time => addPrefix(Math.floor((time / (1000 * 60)) % 60));
const toSeconds = (ime => addPrefix(Math.floor((time / 1000) % 60));
const toMiliseconds = time => Math.floor((time % 1000) / 100);
const milisecondToHoursAndMinute = time => {
const hours = toHours(time);
const minutes = toMinutes(time);
const seconds = toSeconds(time);
const miliseconds = toMiliseconds(time);
return `${hours}:${minutes}:${seconds}.${miliseconds}`
}
let dateTimeStr = new Date(1949778000);
dateTimeStr = Math.floor(dateTimeStr/86400000) +' days '+ dateTimeStr.getHours() +' hours '+ dateTimeStr.getMinutes() +' minutes '+ dateTimeStr.getSeconds() +' seconds';
console.log(dateTimeStr);
You don't have to calculate the days if you don't need them
"22 days 16 hours 36 minutes 18 seconds"
I don't see the need for complication in all these answers, it's easy to add zeros by adding a power of 10:
function timeToString(t) {
const value =
((t / 3600_000 % 24) | 0) * 10000 +
((t / 60_000 % 60) | 0) * 100 +
((t / 1_000 % 60) | 0);
return (1000000 + value).toString().replace(/1(..)(..)(..)/, '$1:$2:$3');
}
If anyone still need here's a modified version of one of the code snippets posted above in js by https://stackoverflow.com/a/58826445/20067539
function timeConversion(duration) {
var portions = [];
var msInDay = 1000 * 60 * 60 * 24
var days = Math.trunc(duration / msInDay);
if (days > 0 ) {
portions.push(days + (days === 1 ? " day" : " days"))
duration = duration - (days * msInDay)
}
var msInHour = 1000 * 60 * 60;
var hours = Math.trunc(duration / msInHour);
if (hours > 0) {
portions.push(hours + (hours === 1 ? ' hour' : ' hours'));
duration = duration - (hours * msInHour);
}
var msInMinute = 1000 * 60;
var minutes = Math.trunc(duration / msInMinute);
if (minutes > 0) {
portions.push(minutes + (minutes === 1 ? ' minute' : ' minutes'));
duration = duration - (minutes * msInMinute);
}
var seconds = Math.trunc(duration / 1000);
if (seconds > 0) {
portions.push(seconds + (seconds === 1 ? ' second' : ' seconds'));
}
return portions.join(' ');
}
console.log(timeConversion((60 * 60 * 1000) + (59 * 60 * 1000) + (59 * 1000)));
console.log(timeConversion((60 * 60 * 1000) + (59 * 60 * 1000)));
console.log(timeConversion((60 * 60 * 1000)));
console.log(timeConversion((60 * 60 * 1000) + (59 * 1000)));
console.log(timeConversion((59 * 60 * 1000) + (59 * 1000)));
console.log(timeConversion((59 * 1000)));

Categories