54
votes

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
@RomainHippeau hi! Yes, my code works, but it really big, I'm looking to a way to shrink it (:ALSD Minecraft
you can use some library such as dateformat.Kai Hao
Are you worried that it's large, or that it's slow? If the former, you can do a bit of refactoring and use a minifier; if the latter, it is really not slow: worrying about doing this each second is like worrying you shouldn't toss your bubblegum into trash because the junkyard might run out of space.Amadan
@Amadan If it isn't slow then great! I want to shrink it because it's too large, just to make it more compact and use less space, but I don't want to minify it. I'm really bad with shorthands but I was aiming towards that!ALSD Minecraft

13 Answers

194
votes

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; 
}
13
votes

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"
    };
6
votes

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.

5
votes

The builtin JavaScript Date object can simplify the required code

 toTime(seconds) {
       var date = new Date(null);
       date.setSeconds(seconds);
       return date.toISOString().substr(11, 8);
    }
4
votes

I'm probably a bit late but you can achieve this kind of things using

https://momentjs.com/

myVar = moment(myVar).format('HH:mm');

moment provides A LOT of format for hours / dates etc.

4
votes

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;
}
3
votes

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;
}
2
votes
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

1
votes

@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

1
votes

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(' ')
}
0
votes

Try this :D

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"
    }
0
votes
 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

-2
votes

Convert to H:M

Number(moment.duration(Number(37320), 'seconds').hours()+'.'+moment.duration(Number(37320),'seconds').minutes())