Converting Seconds to Days, Hours, Minutes and Seconds
In a project I was working on this morning, I had a bit of a headache converting a number of seconds into days, hours, minutes and seconds. It's actually simple, but I was stuck. If you're in the same boat and face a similar problem, here is a solution. For example, we want to trigger an event after 500 seconds.
var basetime = 500;
That would be 0 days, 0 hours, 8 minutes, 20 seconds. It can be calculated like this:
var days = Math.floor(basetime / 86400);
var hours = Math.floor((basetime % 86400) / 3600);
var minutes = Math.floor((basetime % 3600) / 60);
var seconds = Math.floor(basetime % 60);
Math.floor rounds the result down to the next lower whole number. For the number of days we simply divide the variable basetime (= the number of seconds we want to convert) by 86400 (= 60 seconds 60 minutes 24 hours = 1 day) and round down. The remainder of this division (the modulo) is the seconds that are left over and couldn't be "packed" into a day. Divided by 3600 (one hour), that gives the number of remaining hours. We round down again, because we want to "fill up" with minutes. Dividing the number of seconds by 3600 gives us the number of hours that fit into the seconds value. Taking the remainder modulo 3600 and dividing it by 60 gives the number of minutes that are left. Round down, because we want to fill up with seconds. Finally, we take the number of seconds modulo 60 to get the seconds left over. Round down, and we have the time in seconds.
Worked out with actual numbers, the result looks like this:
var basetime = 500;
var days = Math.floor(500 / 86400); // 500 / 86400 = 0.005787037037037 = rounded down 0
var hours = Math.floor((500 % 86400) / 3600); // 500 % 86400 = 500 / 3600 = 0.138888888888889 = rounded down 0
var minutes = Math.floor((basetime % 3600) / 60); // 500 % 3600 = 500 / 60 = 8.33 = rounded down 8
var seconds = Math.floor(basetime % 60); // 500 % 60 = 20 = rounded down 20