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?
You can try this, i have used this successfully in the past
You should be able to add the minutes and seconds on easily
Fiddle
You can change the object to
I think you would find this solution very helpful.
You modify the display format to fit your needs with something like this –
A low fat way to do this is:
Thus
This is easy to understand and extend as needed.
Convert to H:M
I found Wilson Lee’s and Brian’s code super useful! Here is how I adapted their code:
@pkerckhove has already mentioned
moment
as a great library to work with dates and times, and you can also usemoment
to directly format the seconds into OP’s desired format, i.e.:Will result in:
0 hours, 23 minutes and 59 seconds
and,Will result in:
2 hours, 37 minutes and 12 seconds
Try this, Convert SEC to H:M:S.
The builtin JavaScript Date object can simplify the required code
Try this 😀
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.
Will return this format human readable format 00:00:00
console.log(dateForm(16060));
// 1 hours, 0 minutes and 0 seconds
One way of doing it: