Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split down a number in seconds to days, hours, minutes, and seconds?

I've heard that it's possible to accomplish this using the modulus % operator present in most programming languages. The real question is, how? I'm unfamiliar with how modulus works, so I've had difficulties using it in the past. Given the present time here in seconds since 1970, 1307758473.484, how can I calculate how many years that is, days that is, hours that is, and minutes that is using modulus?

I'm essentially looking to format it like this: "5 years, 10 days, 12 hours, 7 minutes, and 18.56 seconds". How would I do this? I'm really interested in learning the logic behind this and not interested in a simple drop-in solution.

like image 993
Naftuli Kay Avatar asked Jun 11 '11 02:06

Naftuli Kay


1 Answers

When you do integer division, you get quotient and remainder. For example,

5 divided by 3 is quotient 1 with remainder 2.

In programming languages, this is usually expressed as:

5 / 3   # => 1
5 % 3   # => 2

The conversion you want is just a repeatation of this. It's easier to to start from the lower unit and go higher on.

First, you have

  • 1307758473.484 seconds

Since 60 seconds is 1 minute, and

1307758473.484 / 60 = 21795974  (intended to be integer division)
1307758473.484 % 60 = 33.484,

it is the same as

  • 21795974 minutes 33.484 seconds

Since 60 minutes is 1 hour, and

21795974 / 60 = 363266
21795974 % 60 = 14

it is further the same as

  • 363266 hours 14 minutes 33.484 seconds

Now, there is a little bit of difficulty. Most days are 24 hours. When there is a leap second, it is not. If you ignore leap seconds and assume 1 day is 24 hours, then, by doing the calculation,

363266 / 24 = 15136
363266 % 24 = 2

it is further the same as

  • 15136 days 2 hours 14 minutes 33.484 seconds.

Similarly, Most years are 365 days. When there is a leap day (year), it is not. If you ignore leap days and assume that 1 year is 365 days, then by doing the calculation,

15136 / 365 = 41
15136 % 365 = 171

it is further the same as

  • 41 years 171 days 2 hours 14 minutes 33.483 seconds
like image 83
sawa Avatar answered Oct 21 '22 17:10

sawa