-2

help me with this one problem. I am confused how to convert second to years, days, hours, minutes and second in JavaScript. This below as an example

convertSeconds(10000)) // 2 hours, 46 minutes and 40 seconds
convertSeconds(62)) // 1 minutes and 2 seconds
convertSeconds(2000000)) // 23 days, 3 hours, 33 minutes and 20 seconds
convertSeconds(126144060)) // 4 years and 1 minutes

I know this task needs modulus just like below :

var days = Math.floor(seconds / (3600*24))
seconds  -= days*3600*24
var hrs   = Math.floor(seconds / 3600)
seconds  -= hrs*3600
var minutes = Math.floor(seconds / 60)
seconds  -= minutes*60

But it doesn't print as I want it like in my comments. How to console like that. Thank you

Liam
  • 27,717
  • 28
  • 128
  • 190
John Doe
  • 9
  • 5
  • 1
    What's `convertSeconds` do? It's really very unclear to me what your question actually is. – Liam Jan 07 '19 at 11:26
  • You can just use console.log(hrs + " hours "+ minutes + " min " + seconds + " sec"); – MJN Jan 07 '19 at 11:31
  • I'm sorry if it wasn't very unclear. What I meant, I wanted the answer just like my test case. If there is no hour then hour doesn't need to be printed. – John Doe Jan 07 '19 at 13:19

1 Answers1

-1

if I understand your question, the solution could be:

function convertSeconds(secT){ 

var seconds = secT % 60; 

var minutes = ((secT - seconds)/60) % 60; 

var hours = (secT - seconds - (minutes * 60)) / 3600 % 3600;
//EDIT
var print = "";
If(hours!=0){
    print = print + hours + " hours ";
}
if(minutes!=0){
    print = print + minutes  + " minutes ";
}
if(seconds!=0){
    print = print + seconds + " seconds ";
}
alert(print);
}
Baby
  • 326
  • 4
  • 16