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

前端 未结 3 991
天涯浪人
天涯浪人 2021-02-02 17:06

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 wi

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-02 17:47

    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

提交回复
热议问题