Ruby/Rails:将日期转换为 UNIX 时间戳 [英] Ruby/Rails: converting a Date to a UNIX timestamp

查看:20
本文介绍了Ruby/Rails:将日期转换为 UNIX 时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从 Rails 应用程序中的 Date 对象获取 UNIX 时间戳(自 1970 GMT 以来的秒数)?

How would I get a UNIX timestamp (number of seconds since 1970 GMT) from a Date object in a Rails app?

我知道 Time#to_i 返回一个时间戳,但是执行 Date#to_time 然后获取时间戳会导致大约一个月的时间(不知道为什么...).

I know Time#to_i returns a timestamp, but doing Date#to_time and then getting the timestamp results in something that's off by about a month (not sure why...).

感谢任何帮助,谢谢!

好的,我想我想通了——我在一个循环中多次处理一个日期,每次由于时区不匹配而移动了一点日期,最终导致我的时间戳是一个月的时间.不过,我很想知道是否有任何方法可以在不依赖 Date#to_time 的情况下做到这一点.

OK, I think I figured it out- I was processing a date several times in a loop, and each time the date was moved a little because of a time zone mismatch, ultimately leading to my timestamp being a month off. Still, I'd be interested in knowing if there's any way to do this without relying on Date#to_time.

推荐答案

代码 date.to_time.to_i 应该可以正常工作.下面的 Rails 控制台会话显示了一个示例:

The code date.to_time.to_i should work fine. The Rails console session below shows an example:

>> Date.new(2009,11,26).to_time
=> Thu Nov 26 00:00:00 -0800 2009
>> Date.new(2009,11,26).to_time.to_i
=> 1259222400
>> Time.at(1259222400)
=> Thu Nov 26 00:00:00 -0800 2009

请注意,中间 DateTime 对象是本地时间,因此时间戳可能与您的预期相差几个小时.如果你想在UTC时间工作,你可以使用DateTime的方法to_utc".

Note that the intermediate DateTime object is in local time, so the timestamp might be a several hours off from what you expect. If you want to work in UTC time, you can use the DateTime's method "to_utc".

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

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