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

前端 未结 3 990
天涯浪人
天涯浪人 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 18:02

    Modulus returns the remainder when performing integer division.

    I think its easiest to understand how to use Mod by working backwards through a problem first.

    Lets start simple with hours, minutes and seconds - 1 hour, 10 minutes and 30 seconds to be precise.

    First, you have 30 seconds. This is easy - it's just 30. No brainer. Now add minutes - to determine minutes as seconds you multiply them times 60. Thus 10 minutes and 30 seconds = 630 seconds.

    Now we see how mod works - because if you divide 630 by 60 you get 10.5 but if you ignore the fraction (whole integer division) you get 10. The remainder is the seconds.

    So if you MOD 630 by 60 you get 30 - the remainder left over when dividing 630 by 30.

    So to determine minutes and seconds, divide by 60 for the minutes, and mod by 60 for the seconds.

    Now add an hour. One hour = 60 minutes and 60 minutes is 60*60 seconds so 1 hour = 3600 seconds. 3600 + 600 + 30 = 4230 seconds.

    4230 / 3600 (1 hour) = 1 - so we have one hour

    4230 % (mod) 3600 = 630 - grab this and now we process for minutes.

    So if you flesh this out further and add a day - 1 day = 24 hours = 24*3600 = 86400 86400+3600+600+30 = 90630

    90630 / 86400 = 1 -> 1 day

    90630 % 86400 = 4230 -> seconds left over

    4230 / 3600 = 1 -> 1 hour

    and repeat the above logic.

    Hope that helps clear it up - you keep repeating that iteration further and you can do weeks and years, but months are special since they're irregular, and so are leap years.

提交回复
热议问题