将 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:34:51  来源:igfitidea点击:

Converting Ruby timestamp to seconds in Epoch and back

ruby-on-railsruby

提问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对象,则可以使用strftimestrptime方法。

回答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