How to convert seconds to minutes and hours in javascript

I have a count of seconds stored in variable seconds. I want to convert for example 1439 seconds to 23 minutes and 59 seconds. And if the time is greater than 1 hour (for example 9432 seconds), to 2 hours, 37 minutes and 12 seconds.

How can I achieve this?

I’m thinking of:

var sec, min, hour;

if(seconds<3600){
    var a = Math.floor(seconds/60); //minutes
    var b = seconds%60; //seconds

    if (b!=1){
        sec = "seconds";
    }else{
        sec = "second";
    }

    if(a!=1){
        min = "minutes";
    }else{
        min = "minute";
    }

    $('span').text("You have played "+a+" "+min+" and "+b+" "+sec+".");
}else{
        var a = Math.floor(seconds/3600); //hours
    var x = seconds%3600;
    var b = Math.floor(x/60); //minutes
    var c = seconds%60; //seconds

     if (c!=1){
        sec = "seconds";
    }else{
        sec = "second";
    }

    if(b!=1){
        min = "minutes";
    }else{
        min = "minute";
    }

    if(c!=1){
        hour = "hours";
    }else{
        hour = "hour";
    }

    $('span').text("You have played "+a+" "+hour+", "+b+" "+min+" and "+c+" "+sec+".");
}

But that’s a lot of code, and it has to be calculated each second. How can I shrink this up?

13 thoughts on “How to convert seconds to minutes and hours in javascript”

  1. You can try this, i have used this successfully in the past
    You should be able to add the minutes and seconds on easily

    function secondsToTime(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;
    }
    

    Fiddle

    You can change the object to

    var obj = {
            "h": hours + " hours",
            "m": minutes + " minutes",
            "s": seconds + " seconds"
        };
    
    Reply
  2. I think you would find this solution very helpful.

    You modify the display format to fit your needs with something like this –

    function secondsToHms(d) {
        d = Number(d);
        var h = Math.floor(d / 3600);
        var m = Math.floor(d % 3600 / 60);
        var s = Math.floor(d % 3600 % 60);
    
        var hDisplay = h > 0 ? h + (h == 1 ? " hour, " : " hours, ") : "";
        var mDisplay = m > 0 ? m + (m == 1 ? " minute, " : " minutes, ") : "";
        var sDisplay = s > 0 ? s + (s == 1 ? " second" : " seconds") : "";
        return hDisplay + mDisplay + sDisplay; 
    }
    
    Reply
  3. A low fat way to do this is:

    function seconds_to_days_hours_mins_secs_str(seconds)
    { // day, h, m and s
      var days     = Math.floor(seconds / (24*60*60));
          seconds -= days    * (24*60*60);
      var hours    = Math.floor(seconds / (60*60));
          seconds -= hours   * (60*60);
      var minutes  = Math.floor(seconds / (60));
          seconds -= minutes * (60);
      return ((0<days)?(days+" day, "):"")+hours+"h, "+minutes+"m and "+seconds+"s";
    }
    

    Thus

    > seconds_to_days_hours_mins_secs_str(9432+60*60*24)
    '1 days, 2h, 37m and 12s'
    

    This is easy to understand and extend as needed.

    Reply
  4. I found Wilson Lee’s and Brian’s code super useful! Here is how I adapted their code:

    function formatTime(serverTimeinSeconds, elementId)
    { /* This converts seconds into days, hours, minutes and seconds timestring.
         Requires JQuery if elementId argument is provided */
      seconds = Math.floor(Number(serverTimeinSeconds));
      days = Math.floor(seconds / (24*60*60));
      seconds -= Math.floor(days    * (24*60*60));
      hours    = Math.floor(seconds / (60*60));
      seconds -= Math.floor(hours   * (60*60));
      minutes  = Math.floor(seconds / (60));
      seconds -= Math.floor(minutes * (60));
    
      dDisplay = days > 0 ? days + (days == 1 ? ' day, ' : ' days, ') : '';
      hDisplay = hours > 0 ? hours + (hours == 1 ? ' hour, ' : ' hours, ') : '';
      mDisplay = minutes > 0 ? minutes + (minutes == 1 ? ' minute, ' : ' minutes, ') : '';
      sDisplay = seconds > 0 ? seconds + (seconds == 1 ? ' second' : ' seconds') : '';
    
      if (elementId != null) {
        if (serverTimeinSeconds < 60) {
            $(elementId).css('font-size', '15px');
            $(elementId).html(sDisplay);
        }
        if (serverTimeinSeconds >= 60 && serverTimeinSeconds < 3600) {
            $(elementId).css('font-size', '15px');
            $(elementId).html(mDisplay + sDisplay);
        }
        if (serverTimeinSeconds >= 3600 && serverTimeinSeconds < 86400) {
            $(elementId).css('font-size', '12px');
            $(elementId).html(hDisplay + mDisplay + sDisplay);
        }
        if (serverTimeinSeconds >= 86400 && serverTimeinSeconds !== Infinity) {
            $(elementId).css('font-size', '8px');
            $(elementId).html(dDisplay + hDisplay + mDisplay + sDisplay);
        }
      }
      return dDisplay + hDisplay + mDisplay + sDisplay;
    }
    
    Reply
  5. @pkerckhove has already mentioned moment as a great library to work with dates and times, and you can also use moment to directly format the seconds into OP’s desired format, i.e.:

    import moment from 'moment'
    
    const myVar = 1439
    console.log(
        moment.unix(myVar).utc().format('H [hours,] m [minutes and] s [seconds]')
    )
    

    Will result in: 0 hours, 23 minutes and 59 seconds and,

    import moment from 'moment'
    
    const myVar = 9432
    console.log(
        moment.unix(myVar).utc().format('H [hours,] m [minutes and] s [seconds]')
    )
    

    Will result in: 2 hours, 37 minutes and 12 seconds

    Reply
  6. Try this, Convert SEC to H:M:S.

    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;
    }
    
    Reply
  7. Try this 😀

    secondsToHms(d) {
            d = Number(d);
            var h = Math.floor(d / 3600);
            var m = Math.floor(d % 3600 / 60);
            var s = Math.floor(d % 3600 % 60);
    
            var hDisplay = h > 0 ? h + (h == 1 ? "" : "") : "";
            var mDisplay = m > 0 ? m + (m == 1 ? "" : "") : "";
            var sDisplay = s > 0 ? s + (s == 1 ? "" : "") : "";
            if (hDisplay != "") {
                return (hDisplay.length > 1 ? hDisplay : '0' + hDisplay) + ":" + (mDisplay.length > 1 ? mDisplay : '0' + mDisplay) + ":" + (sDisplay.length > 1 ? sDisplay : '0' + sDisplay);
            }
            else if (mDisplay != "") {
                return (mDisplay.length > 1 ? mDisplay : '0' + mDisplay) + ":" + (sDisplay.length > 1 ? sDisplay : '0' + sDisplay);
            }
            else if (sDisplay != "") {
                return "00:" + (sDisplay.length > 1 ? sDisplay : '0' + sDisplay);
            }
            return "00:00"
        }
    
    Reply
  8.  const formatter = (seconds = 0) => {
      const d = Number(secondsAmount);
      const h = Math.floor(d / 3600);
      const m = Math.floor((d % 3600) / 60);
      const s = Math.floor((d % 3600) % 60);
      const hDisplay = h > 0 ? `${h.toString().length > 1 ? `${h}` : `${0}${h}`}` : '00';
      const mDisplay = m > 0 ? `${m.toString().length > 1 ? `${m}` : `${0}${m}`}` : '00';
      const sDisplay = s > 0 ? `${s.toString().length > 1 ? `${s}` : `${0}${s}`}` : '00';
      return `${hDisplay}:${mDisplay}:${sDisplay}`;
    };
    

    Will return this format human readable format 00:00:00

    Reply
  9. Please install moment js after that import it,
    
    import moment from 'moment'
    
    let dateForm = (arg) => {
        return moment.unix(arg).utc().format('H [hours,] m [minutes and] s [seconds]');
    }
    
    console.log(dateForm(11));
    // 0 hours, 0 minutes and 11 seconds
    

    console.log(dateForm(16060));
    // 1 hours, 0 minutes and 0 seconds

    Reply
  10. One way of doing it:

    const formatDuration = totalSeconds => {
      const hours = Math.floor(totalSeconds / 3600)
      const minutes = Math.floor((totalSeconds % 3600) / 60)
      const seconds = totalSeconds - hours * 3600 - minutes * 60
    
      return [`${hours}h`, `${minutes}m`, `${seconds}s`]
        .filter(item => item[0] !== '0')
        .join(' ')
    }
    
    Reply

Leave a Comment