问题描述
我听说可以使用大多数编程语言中提供的模数%
运算符来完成此操作.真正的问题是,如何?我不熟悉模数的工作原理,因此过去很难使用它.给定这里的当前时间以秒为单位,即1970年以来的秒数,我该如何计算使用模数的年数,即天数,小时数和分钟数?
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?
我基本上希望将其格式化为:"5年10天12小时7分钟18.56秒".我该怎么做?我真的很想了解这个背后的逻辑,而对简单的嵌入式解决方案不感兴趣.
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.
推荐答案
进行整数除法时,将得到商和余数.例如,
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.
首先,你有
-
1307758473.484 seconds
因为60秒是1分钟,并且
Since 60 seconds is 1 minute, and
1307758473.484 / 60 = 21795974 (intended to be integer division)
1307758473.484 % 60 = 33.484,
与
-
21795974 minutes 33.484 seconds
因为60分钟是1个小时,并且
Since 60 minutes is 1 hour, and
21795974 / 60 = 363266
21795974 % 60 = 14
进一步与
-
363266 hours 14 minutes 33.484 seconds
现在,有点困难了.大部分时间是24小时.如果有a秒,就没有.如果您忽略leap秒,并假设1天为24小时,那么通过计算,
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
进一步与
-
15136 days 2 hours 14 minutes 33.484 seconds
.
类似地,大多数年份是365天.如果有a日(年),则没有.如果您忽略leap日,并假设1年为365天,那么通过计算,
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
它与
-
41 years 171 days 2 hours 14 minutes 33.483 seconds
这篇关于将数字以秒为单位拆分为天,小时,分钟和秒?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!