Ruby/Rails-如何将秒转换为时间? [英] Ruby/Rails - How to convert seconds to time?

查看:332
本文介绍了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是距纪元的秒数​​:

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?

推荐答案

最简单的单行代码会忽略日期:

The simplest one-liner simply ignores the date:

Time.at(82800).utc.strftime("%I:%M%p")

#-> "11:00PM"

这篇关于Ruby/Rails-如何将秒转换为时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆