将 Ruby 时间戳转换为 Epoch 中的秒数并返回
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15263767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converting Ruby timestamp to seconds in Epoch and back
提问by MichaelScaria
I have a field in my database that is stored as a timestamp, I need to output this in seconds in EPOCH time.
我的数据库中有一个字段存储为时间戳,我需要在 EPOCH 时间以秒为单位输出它。
回答by bert bruynooghe
Supposing your timestamp is a Ruby Timeobject:
假设您的时间戳是一个 Ruby Time对象:
puts time_stamp.strftime('%s')
puts time_stamp.to_i
timestamp = Time.at(628232400)
In case it is a DateTimeobject, you have the strftimeand strptimemethods at your disposal.
如果它是DateTime对象,则可以使用strftime和strptime方法。
回答by Sachin R
Returns number of seconds since epoch:
返回自纪元以来的秒数:
time = Time.now.to_i
Returns second since epoch which includes microseconds:
返回自纪元以来的秒数,其中包括微秒:
time = Time.now.to_f
回答by Martin K
Time.now.to_i
returns the Epoch. Same goes for:
返回纪元。同样适用于:
time = Time.now
time.to_i

