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

查看:728
本文介绍了Ruby / Rails:将Date转换为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?

我知道时间#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:将Date转换为UNIX时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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