419

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 converting to x hours and x minutes format.

So is there a tiny snippet that does this in jQuery or just raw JavaScript?

2

48 Answers 48

708
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());

18
  • 26
    use "%" operator >> var minutes = Math.floor((sec_num % 3600) / 60); var seconds = Math.floor(sec_num % 60);
    – IvanM
    Mar 31, 2014 at 12:50
  • 3
    ah thanks. I don't see it working both ways as a string until you call .toString() on the integer. you can make it work the other way around by parsing int too
    – Sonic Soul
    Jun 26, 2015 at 21:13
  • 90
    Don't put in on the prototype, just make a utility function. Oct 7, 2015 at 17:42
  • 44
    modify prototype for such thing? 390 upvotes? seriously? May 26, 2017 at 14:32
  • 4
    This will fail for certain values and seconds end up showing up as 60. Example 00:14:60. Surprised with the high number of up votes on this solution and nobody seemed to actually test it out thoroughly.
    – Johann
    May 7, 2019 at 18:17
371

You can manage to do this without any external JS library with the help of JS Date method like following:

var date = new Date(0);
date.setSeconds(45); // specify value for SECONDS here
var timeString = date.toISOString().substring(11, 19);
console.log(timeString)

10
  • 13
    Why is this answer with so low? I get it in 2011 probably IE 7 and 8 was the base which will not support it, but it's end of 2014, so this simple plain, fuss free solution should be way higher. Dec 10, 2014 at 13:27
  • 73
    I like this answer. It can be even shorter: new Date(1000 * seconds).toISOString().substr(11, 8). Aug 17, 2016 at 12:00
  • 11
    Nice answer. You can use .replace(/^[0:]+/, "") after substr to remove all zeroes and : from the start of the string.
    – Palo
    Feb 11, 2017 at 13:44
  • 6
    Add this in front to handle time over 24h. parseInt(d / 86400) + "d "
    – Tofandel
    Oct 17, 2019 at 0:17
  • 38
    This breaks if the duration is longer than 23:59:59.
    – sim642
    Sep 26, 2020 at 9:05
84

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)

15
  • 8
    +1 - Super-simple; thanks! Just used a variant of this to only show the minutes and seconds: var myDate = new Date().toTimeString().replace(/.*(\d{2}:\d{2})(:\d{2}).*/, "$1"); May 17, 2013 at 15:11
  • 1
    shouldn't that be "new Date(null, null, null, null, null, timeInSecs).toTimeString().replace(/.*(\d{2}:)(\d{2}:\d{2}).*/, "$2")" ?
    – overbyte
    Aug 27, 2013 at 15:36
  • 6
    The use of replace is confusing. Why not use new Date(null, null, null, null, null, timeInSeconds).toTimeString().match(/\d{2}:\d{2}:\d{2}/)[0] ? Jan 4, 2014 at 19:17
  • 7
    This is fine for showing a given time, but note the question (and other answers here) are about showing a duration, i.e. a given number of seconds independent of the current time.
    – mahemoff
    Sep 29, 2014 at 19:34
  • 6
    Simpler version of this: new Date().toTimeString().split(" ")[0]
    – Henrik N
    Apr 15, 2016 at 7:58
63

I recommend ordinary javascript, using the Date object. (For a shorter solution, using toTimeString, see the second code snippet.)

var seconds = 9999;
// multiply by 1000 because Date() requires miliseconds
var date = new Date(seconds * 1000);
var hh = date.getUTCHours();
var mm = date.getUTCMinutes();
var ss = date.getSeconds();
// If you were building a timestamp instead of a duration, you would uncomment the following line to get 12-hour (not 24) time
// if (hh > 12) {hh = hh % 12;}
// These lines ensure you have two-digits
if (hh < 10) {hh = "0"+hh;}
if (mm < 10) {mm = "0"+mm;}
if (ss < 10) {ss = "0"+ss;}
// This formats your string to HH:MM:SS
var t = hh+":"+mm+":"+ss;
document.write(t);

(Of course, the Date object created will have an actual date associated with it, but that data is extraneous, so for these purposes, you don't have to worry about it.)


Edit (short solution):

Make use of the toTimeString function and split on the whitespace:

var seconds = 9999; // Some arbitrary value
var date = new Date(seconds * 1000); // multiply by 1000 because Date() requires miliseconds
var timeStr = date.toTimeString().split(' ')[0];

toTimeString gives '16:54:58 GMT-0800 (PST)', and splitting on the first whitespace gives '16:54:58'.

9
  • It seems to make the date in the local time zone, which in my case adds 1 hour to the time. With seconds=0, I get "01:00:00" (Thu Jan 01 1970 01:00:00 GMT+0100 (CET)), which is wrong.
    – mivk
    Jun 7, 2013 at 15:12
  • 3
    I get a correct result if I use date.getUTCHours() and date.getUTCMinutes().
    – mivk
    Jun 7, 2013 at 16:52
  • 9
    I like this, but it does assume the duration is less than 24h
    – Rory
    Jan 28, 2018 at 0:20
  • 1
    Add parseInt(d / 86400) + "d " in front to handle cases over 24h
    – Tofandel
    Oct 17, 2019 at 0:14
  • 3
    Timezones hate this.
    – Ryan Leach
    Dec 10, 2020 at 14:47
55

Here's my take on it:

function formatTime(ms: number) {
  const seconds = Math.floor(Math.abs(ms / 1000))
  const h = Math.floor(seconds / 3600)
  const m = Math.floor((seconds % 3600) / 60)
  const s = Math.round(seconds % 60)
  const t = [h, m > 9 ? m : h ? '0' + m : m || '0', s > 9 ? s : '0' + s]
    .filter(Boolean)
    .join(':')
  return ms < 0 && seconds ? `-${t}` : t
}

Expected results:

import assert from 'assert'
assert.equal(formatTime(0), '0:00')
assert.equal(formatTime(1_000), '0:01')
assert.equal(formatTime(599_000), '9:59')
assert.equal(formatTime(600_000), '10:00')
assert.equal(formatTime(3600_000), '1:00:00')
assert.equal(formatTime(360009_000), '100:00:09')
assert.equal(formatTime(200), '0:00')
assert.equal(formatTime(-200), '0:00')
assert.equal(formatTime(-1_000), '-0:01')
11
  • 3
    @RubenStolk I find it a bit confusing to have a function that takes two second arguments. I find my version clearer even if it's a bit more verbose. Jan 8, 2018 at 22:58
  • 1
    @pstanton trailing comma is supported since IE9: caniuse.com/#feat=mdn-javascript_grammar_trailing_commas . I personally choose to ignore those old browsers now. But you're right, I removed it so the answer is more generic. Feb 6, 2020 at 14:56
  • 2
    Great solution. Maybe just change seconds as const s = Math.round(seconds % 60);
    – Raff
    Apr 3, 2020 at 13:06
  • 1
    Actually, you're right. The input seconds could have decimals. So I'll change it 👍 Apr 5, 2020 at 17:25
  • 1
    Thanks, this is exactly what I was looking for. Just like Youtube's. Aug 5, 2021 at 3:10
45

A Google search turned up this result:

function secondsToTime(secs)
{
    secs = Math.round(secs);
    var hours = Math.floor(secs / (60 * 60));

    var divisor_for_minutes = secs % (60 * 60);
    var minutes = Math.floor(divisor_for_minutes / 60);

    var divisor_for_seconds = divisor_for_minutes % 60;
    var seconds = Math.ceil(divisor_for_seconds);

    var obj = {
        "h": hours,
        "m": minutes,
        "s": seconds
    };
    return obj;
}
1
  • 8
    secondsToTime(119.9) => Object {h: 0, m: 1, s: 60}. To fix this, add secs = Math.round(secs); at the beginning of the method. Of course, we saw this bug during the demo... Nov 18, 2013 at 11:15
33
function formatTime(seconds) {
    return [
        parseInt(seconds / 60 / 60),
        parseInt(seconds / 60 % 60),
        parseInt(seconds % 60)
    ]
        .join(":")
        .replace(/\b(\d)\b/g, "0$1")
}
6
  • 1
    Further explanation on why this answer would work for the questioner or what may have been wrong in the original question would help raise the quality of this answer. Apr 18, 2017 at 8:43
  • 2
    Pretty self explainatory and good answer, reduced and simplified the top answer.
    – AlexioVay
    Dec 17, 2017 at 8:54
  • 1
    Short and sweet, very good. Suggest replacing parseInt with Math.floor esp. if using TypeScript (parseInt should have string input)
    – Aaron B
    Dec 23, 2021 at 21:53
  • 2
    parseInt requires a string, so seconds must be a string. In TypeScript, if seconds is a number, use Math.floor instead of parseInt. Mar 3, 2022 at 11:29
  • 1
    Suggestion: remove the parseInt and instead place .map(Math.floor) before .join(':'). Also, for better readability, instead of .replace(/\b(\d)\b/g, "0$1") after the .join(), one could use .map(n => n.toString().padStart(2, '0')) before the .join().
    – Chris
    Jan 2, 2023 at 17:07
32

Variation on a theme. Handles single digit seconds a little differently

seconds2time(0)  ->  "0s" 
seconds2time(59) -> "59s" 
seconds2time(60) -> "1:00" 
seconds2time(1000) -> "16:40" 
seconds2time(4000) -> "1:06:40"

function seconds2time (seconds) {
    var hours   = Math.floor(seconds / 3600);
    var minutes = Math.floor((seconds - (hours * 3600)) / 60);
    var seconds = seconds - (hours * 3600) - (minutes * 60);
    var time = "";

    if (hours != 0) {
      time = hours+":";
    }
    if (minutes != 0 || time !== "") {
      minutes = (minutes < 10 && time !== "") ? "0"+minutes : String(minutes);
      time += minutes+":";
    }
    if (time === "") {
      time = seconds+"s";
    }
    else {
      time += (seconds < 10) ? "0"+seconds : String(seconds);
    }
    return time;
}
0
15

Using the amazing moment.js library:

function humanizeDuration(input, units ) { 
  // units is a string with possible values of y, M, w, d, h, m, s, ms
  var duration = moment().startOf('day').add(units, input),
    format = "";

  if(duration.hour() > 0){ format += "H [hours] "; }

  if(duration.minute() > 0){ format += "m [minutes] "; }

  format += " s [seconds]";

  return duration.format(format);
}

This allows you to specify any duration be it hours, minutes, seconds, mills, and returns a human readable version.

15

I like the first answer. There some optimisations:

  • source data is a Number. additional calculations is not needed.

  • much excess computing

Result code:

Number.prototype.toHHMMSS = function () {
    var seconds = Math.floor(this),
        hours = Math.floor(seconds / 3600);
    seconds -= hours*3600;
    var minutes = Math.floor(seconds / 60);
    seconds -= minutes*60;

    if (hours   < 10) {hours   = "0"+hours;}
    if (minutes < 10) {minutes = "0"+minutes;}
    if (seconds < 10) {seconds = "0"+seconds;}
    return hours+':'+minutes+':'+seconds;
}
5
  • 1
    I think this function is a feature used in the fronted and therefor I prototype String and not Number. And Number can always be a string but not the other way round.
    – powtac
    Nov 13, 2012 at 20:43
  • 4
    I think Number is right because seconds is, in fact, a number. you should convert from string before using this function, which is the right thing to do!
    – caesarsol
    Dec 3, 2013 at 9:55
  • 4
    upvoted answer, just like this one, are bad. I bet you don't need ALL numbers to have this method. Do not modify prototype for random utility stuff. May 26, 2017 at 14:34
  • or just to prototype and make it a function numToHHMMSS or strTOHHMMSS
    – yeahdixon
    Jan 21, 2019 at 22:57
  • This solution works while the chosen solution generates seconds of 60 for certain values.
    – Johann
    May 7, 2019 at 18:26
15

Here is an example of using Date.prototype.toLocaleTimeString(). I chose GB as the language, because the US shows a 24 instead of a 00 for the initial hour. Furthermore, I chose Etc/UTC as the time zone, because UTC is aliased to it in the list of tz database time zones.

const formatTime = (seconds) =>
  new Date(seconds * 1000).toLocaleTimeString('en-GB', {
    timeZone:'Etc/UTC',
    hour12: false,
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });

console.log(formatTime(75)); // 00:01:15
.as-console-wrapper { top: 0; max-height: 100% !important; }

Here is the same example, but with Intl.DateTimeFormat. This variant lets you instantiate a reusable formatter object, which is more performant.

const dateFormatter = new Intl.DateTimeFormat('en-GB', {
  timeZone:'Etc/UTC',
  hour12: false,
  hour: '2-digit',
  minute: '2-digit',
  second: '2-digit'
});

const formatTime = (seconds) => dateFormatter.format(new Date(seconds * 1000));

console.log(formatTime(75)); // 00:01:15
.as-console-wrapper { top: 0; max-height: 100% !important; }

2
  • If the time is larger than 24 hours (86400 seconds), this is going to give wrong results
    – Tim
    Jul 20, 2021 at 11:44
  • This is amazingly clever. Thanks!
    – akirk
    Aug 2, 2021 at 9:43
14

It's pretty easy,

function toTimeString(seconds) {
  return (new Date(seconds * 1000)).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0];
}
1
  • This only works if your time duration is less than 1 day. But otherwise, pretty nice.
    – cjbarth
    Nov 12, 2015 at 15:35
11

new Date().toString().split(" ")[4];

result 15:08:03

1
  • Nice - thanks! And a small improvement I made for my needs was to convert a duration in milliseconds to HH:MM:SS -- new Date(new Date().getTime() - startTime).toUTCString().split(" ")[4] where startTime was set previously using startTime = new Date().getTime();. (I had to use toUTCString() because otherwise the times were an hour out.)
    – IpsRich
    Mar 17, 2015 at 10:06
11

Easiest way to do it.

new Date(sec * 1000).toISOString().substr(11, 8)
1
  • 4
    FYI this is modulo 24h so if you input the equivalent of 25 hours it'll appear as 1 hour. Be careful
    – maxime1992
    Nov 30, 2020 at 16:17
8
s2t=function (t){
  return parseInt(t/86400)+'d '+(new Date(t%86400*1000)).toUTCString().replace(/.*(\d{2}):(\d{2}):(\d{2}).*/, "$1h $2m $3s");
}

s2t(123456);

result:

1d 10h 17m 36s
8

I liked Webjins answer the most, so i extended it to display days with a d suffix, made display conditional and included a s suffix on plain seconds:

function sec2str(t){
    var d = Math.floor(t/86400),
        h = ('0'+Math.floor(t/3600) % 24).slice(-2),
        m = ('0'+Math.floor(t/60)%60).slice(-2),
        s = ('0' + t % 60).slice(-2);
    return (d>0?d+'d ':'')+(h>0?h+':':'')+(m>0?m+':':'')+(t>60?s:s+'s');
}

returns "3d 16:32:12" or "16:32:12" or "32:12" or "12s"

4
  • This will be incorrect for durations of 24 days or longer Dec 7, 2015 at 20:54
  • why are you comparing strings greater of 0?
    – Jimmy Kane
    Apr 13, 2018 at 22:10
  • @JimmyKane because automatic typecasting - i looove it! (plus: code is more easy to read (you've got typecasting for a reason, but let's stop trolling (the both of us)). plus: the function would fail only if t is NaN - so if you want security: do it at the input!)
    – nïkö
    Apr 23, 2019 at 16:21
  • @nïkö Ok I understand but more strict new JS versions , linters etc can complain about that. Just saying, dong get me wrong. I like your answer
    – Jimmy Kane
    Apr 24, 2019 at 17:09
7

I loved Powtac's answer, but I wanted to use it in angular.js, so I created a filter using his code.

.filter('HHMMSS', ['$filter', function ($filter) {
    return function (input, decimals) {
        var sec_num = parseInt(input, 10),
            decimal = parseFloat(input) - sec_num,
            hours   = Math.floor(sec_num / 3600),
            minutes = Math.floor((sec_num - (hours * 3600)) / 60),
            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;}
        var time    = hours+':'+minutes+':'+seconds;
        if (decimals > 0) {
            time += '.' + $filter('number')(decimal, decimals).substr(2);
        }
        return time;
    };
}])

It's functionally identical, except that I added in an optional decimals field to display fractional seconds. Use it like you would any other filter:

{{ elapsedTime | HHMMSS }} displays: 01:23:45

{{ elapsedTime | HHMMSS : 3 }} displays: 01:23:45.678

1
  • I have two datetime object and and i want to calculate difference of this 2 datetime object and return output like in this format :Hour : Minutes :Seconds with double digit like : 01 : 02 : 45.Can you please tell me or guide me little with your code?? Jul 5, 2016 at 16:32
4

Here is yet another version, which handles days also:

function FormatSecondsAsDurationString( seconds )
{
    var s = "";

    var days = Math.floor( ( seconds / 3600 ) / 24 );
    if ( days >= 1 )
    {
        s += days.toString() + " day" + ( ( days == 1 ) ? "" : "s" ) + " + ";
        seconds -= days * 24 * 3600;
    }

    var hours = Math.floor( seconds / 3600 );
    s += GetPaddedIntString( hours.toString(), 2 ) + ":";
    seconds -= hours * 3600;

    var minutes = Math.floor( seconds / 60 );
    s += GetPaddedIntString( minutes.toString(), 2 ) + ":";
    seconds -= minutes * 60;

    s += GetPaddedIntString( Math.floor( seconds ).toString(), 2 );

    return s;
}

function GetPaddedIntString( n, numDigits )
{
    var nPadded = n;
    for ( ; nPadded.length < numDigits ; )
    {
        nPadded = "0" + nPadded;
    }

    return nPadded;
}
4
function toHHMMSS(seconds) {
    var h, m, s, result='';
    // HOURs
    h = Math.floor(seconds/3600);
    seconds -= h*3600;
    if(h){
        result = h<10 ? '0'+h+':' : h+':';
    }
    // MINUTEs
    m = Math.floor(seconds/60);
    seconds -= m*60;
    result += m<10 ? '0'+m+':' : m+':';
    // SECONDs
    s=seconds%60;
    result += s<10 ? '0'+s : s;
    return result;
}

Examples

    toHHMMSS(111); 
    "01:51"

    toHHMMSS(4444);
    "01:14:04"

    toHHMMSS(33);
    "00:33"
1
  • I'd put a Math.floor() on the seconds as well since they might be given in decimals. (Happened with me.)
    – Winter
    Sep 11, 2016 at 16:02
4

The most general answer to this is

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"

See explanation at https://stackoverflow.com/a/66504936/1310733

4
function secToTime(seconds, separator) {
    return [
        parseInt(seconds / 60 / 60),
        parseInt(seconds / 60 % 60),
        parseInt(seconds % 60)
    ].join(separator ? separator : ':')
    .replace(/\b(\d)\b/g, "0$1").replace(/^00\:/,'')
}

You can use it now like:

alert(secToTime("123"));

Working snippet:

function secToTime(seconds, separator) {
return [
    parseInt(seconds / 60 / 60),
    parseInt(seconds / 60 % 60),
    parseInt(seconds % 60)
].join(separator ? separator : ':')
.replace(/\b(\d)\b/g, "0$1").replace(/^00\:/,'')
}

console.log(secToTime("123"));

3

I think performance wise this is by far the fastest:

var t = 34236; // your seconds
var time = ('0'+Math.floor(t/3600) % 24).slice(-2)+':'+('0'+Math.floor(t/60)%60).slice(-2)+':'+('0' + t % 60).slice(-2)
//would output: 09:30:36
2
  • Really Awesome. Congrats! Sep 28, 2018 at 17:51
  • Nice ... and >24 hrs safe.
    – Jeffz
    Nov 15, 2018 at 4:18
2

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))
};
0
2

You can use the following function to convert time (in seconds) to HH:MM:SS format :

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

Demo

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 : ':' );
}

document.body.innerHTML = '<pre>' + JSON.stringify({
    5.3515555 : convertTime(5.3515555),
    126.2344452 : convertTime(126.2344452, '-'),
    1156.1535548 : convertTime(1156.1535548, '.'),
    9178.1351559 : convertTime(9178.1351559, ':'),
    13555.3515135 : convertTime(13555.3515135, ',')
}, null, '\t') +  '</pre>';

See also this Fiddle.

2

There's a new method for strings on the block: padStart

const str = '5';
str.padStart(2, '0'); // 05

Here is a sample use case: YouTube durations in 4 lines of JavaScript

1
  • This should be a comment under an answer Jun 27, 2021 at 3:33
2

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

2

A regular expression can be used to match the time substring in the string returned from the toString() method of the Date object, which is formatted as follows: "Thu Jul 05 2012 02:45:12 GMT+0100 (GMT Daylight Time)". Note that this solution uses the time since the epoch: midnight of January 1, 1970. This solution can be a one-liner, though splitting it up makes it much easier to understand.

function secondsToTime(seconds) {
    const start = new Date(1970, 1, 1, 0, 0, 0, 0).getTime();
    const end = new Date(1970, 1, 1, 0, 0, parseInt(seconds), 0).getTime();
    const duration = end - start;

    return new Date(duration).toString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
}
1
  • Timezones hate this. question is about converting seconds into a duration.
    – Ryan Leach
    Dec 10, 2020 at 14:50
2

Here is a fairly simple solution that rounds to the nearest second!

var returnElapsedTime = function(epoch) {
  //We are assuming that the epoch is in seconds
  var hours = epoch / 3600,
      minutes = (hours % 1) * 60,
      seconds = (minutes % 1) * 60;
  return Math.floor(hours) + ":" + Math.floor(minutes) + ":" + Math.round(seconds);
}

2

This is one I wrote recently for MM:SS. It's not exact to the question, but it's a different one-liner format.

const time = 60 * 2 + 35; // 2 minutes, 35 seconds
const str = (~~(time / 60) + "").padStart(2, '0') + ":" + (~~((time / 60) % 1 * 60) + "").padStart(2, '0');

str // 02:35

Edit: This was added for variety, but the best solution here is https://stackoverflow.com/a/25279399/639679 below.

1

This is how i did it

function timeFromSecs(seconds)
{
    return(
    Math.floor(seconds/86400)+'d :'+
    Math.floor(((seconds/86400)%1)*24)+'h : '+
    Math.floor(((seconds/3600)%1)*60)+'m : '+
    Math.round(((seconds/60)%1)*60)+'s');
}

timeFromSecs(22341938) will return '258d 14h 5m 38s'

Not the answer you're looking for? Browse other questions tagged or ask your own question.