Get hours, minutes and seconds from a number without maths operations

Today I’m gonna show you a secret ninja technique to extract hours, minutes and seconds from a number (representing an amount of seconds). In my example I will show an Actionscript code, but this can be implemented in JavaScript and maybe other languages too.
So, the scenario is the following: we have a number representing seconds and we want to know how many hours this amount of seconds contains, how many minutes and how many remaining seconds. We know that a minute is composed by 60 seconds and an hour by 60 minutes and we could write a series of maths operations in order to accomplish our objective, but there is a way far simple and fast: use the Date class!
Date class already implements all the methods we need:

  • getHours()
  • getMinutes()
  • getSeconds()

So, in order to take advantage of these useful methods, all we have to do is initialize a “fake” date using the amount of seconds we want to “split” into hours, minutes and seconds. The Date class has several OPTIONAL arguments that can be specified during its initializations, these are:

  • year
  • month
  • date (day number)
  • hours
  • minutes
  • seconds
  • milliseconds

Because theme all are optional, we can create a date object by specifying only the know arguments (in our case seconds) and by assigning null or zero to the others:

var date:Date = new Date(null, null, null, 0, 0, 9137);

Then by calling getHours, getMinutes and getSeconds we will obtain what we expect:

trace("hours: ", date.getHours()); // 2 hours
trace("minutes: ", date.getMinutes()); // 32 minutes
trace("seconds: ", date.getSeconds()); // 17 seconds

Not sure about the result? Let’s test it:

60 * 60 * 2 = 7200; (seconds contained in 2 hours)
32 * 60 = 1920; (seconds contained in 32 minutes)
7200 + 1920 + 17 = 9137; (original seconds!)

  • Ron Smith

    Thanks a lot Dave. I spent a whole day looking for a solution to extracting hours, minutes and seconds from a pair of d.getTime()s executed at different intervals. Using % (modulus) came to mind at first; what a pain (ugly too). Your solution was, by far, the easiest for me to grasp. Gratitude my friend! I no longer have a headache, and I can turn in for the evening a little earlier, thanks to you. :)

  • Julio Licona

    Thanks a lot exactly the answer that i want

  • plextor

    this is great, but how would you go by calculating hours say if clocking in at work.

  • Ambar Ayu Susilowati

    great! thanks a lot :)