Ruby/Rails - 如何将秒转换为时间?
我需要执行以下转换:
0 -> 12.00AM
1800 -> 12.30AM
3600 -> 01.00AM
...
82800 -> 11.00PM
84600 -> 11.30PM
我想出了这个:
(0..84600).step(1800){|n| puts "#{n.to_s} #{Time.at(n).strftime("%I:%M%p")}"}
这给了我错误的时间,因为 Time.at(n) 期望 n 是从纪元开始的秒数:
0 -> 07:00PM
1800 -> 07:30PM
3600 -> 08:00PM
...
82800 -> 06:00PM
84600 -> 06:30PM
什么是最优化的、与时区无关的解决方案这个转变?
I need to perform the following conversion:
0 -> 12.00AM
1800 -> 12.30AM
3600 -> 01.00AM
...
82800 -> 11.00PM
84600 -> 11.30PM
I came up with this:
(0..84600).step(1800){|n| puts "#{n.to_s} #{Time.at(n).strftime("%I:%M%p")}"}
which gives me the wrong time, because Time.at(n) expects n to be number of seconds from epoch:
0 -> 07:00PM
1800 -> 07:30PM
3600 -> 08:00PM
...
82800 -> 06:00PM
84600 -> 06:30PM
What would be the most optimal, time zone independent solution for this transformation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
最简单的一句话就是忽略日期:
The simplest one-liner simply ignores the date:
不确定这是否
比斯蒂芬更好
Not sure if this is better than
Stephan
两个优惠:
精心设计的 DIY 解决方案:
时间解决方案:
HTH
Two offers:
The elaborate DIY solution:
the Time solution:
HTH
在其他解决方案中,当跨越 24 小时日界限时,小时计数器将重置为 00。另请注意
Time.at
向下舍入,因此如果输入有任何小数秒(例如,当t=479.9
thenTime.at(t).utc.strftime("%H:%M:%S")
将给出00:07:59
而不是 00:08:00` 这是正确的一个)。如果您想要一种方法将任何秒数(甚至大于 24 小时日跨度的高计数)转换为不断增加的 HH:MM:SS 计数器,并处理潜在的小数秒数,请尝试以下操作:
修改自 @springerigor 和建议在 https://gist.github.com/shunchu/3175001 的讨论中
In other solutions, the hour-counter would be reset to 00 when crossing 24-hour day boundaries. Also beware that
Time.at
rounds down, so it will give the wrong result if the input has any fractional seconds (f.ex. whent=479.9
thenTime.at(t).utc.strftime("%H:%M:%S")
will give00:07:59
and not 00:08:00` which is the correct one).If you want a way to convert any number of seconds (even high counts larger than 24-hour day spans) into an ever increasing HH:MM:SS counter, and handle potential fractional seconds, then try this:
Modified from @springerigor's and suggestion in the discussion at https://gist.github.com/shunchu/3175001