ruby 中的时间操作 [英] Time manipulation in ruby
问题描述
我想创建一个位于未来 20 分 10 秒的 DateTime 实例.我在 irb 中尝试使用 Time 和 DateTime,但似乎无法找到真正有意义的方法.我只能向 DateTime 对象添加天数,而只能向 Time 对象添加秒数.
I want to create a DateTime instance that lies 20 minutes and 10 seconds in the future. I tried around with Time and DateTime in irb, but can't seem to figure out a way that really makes sense. I can only add days to DateTime objects and only add seconds to the Time objects.
没有比总是将我想要添加的时间转换为秒更好的方法了吗?
Isn't there a better way than to always convert the time I want to add into seconds?
推荐答案
A Time
是自一个纪元以来的秒数,而 DateTime
是自纪元以来的天数一个时代,这就是为什么将 1
添加到 DateTime
会增加一整天.但是,您可以添加一天的分数,例如
A Time
is a number of seconds since an epoch whereas a DateTime
is a number of days since an epoch which is why adding 1
to a DateTime
adds a whole day. You can however add fractions of a day, for example
d = DateTime.now
d + Rational(10, 86400)
将为 d
添加 10 秒(因为一天有 86400 秒).
Will add 10 seconds to d
(since there are 86400 seconds in a day).
如果您使用的是 Rails,Active Support 会添加一些辅助方法,您可以这样做
If you are using Rails, Active Support adds some helper methods and you can do
d + 20.minutes + 10.seconds
正确的做法是 d
是 DateTime
或 Time
.您可以单独使用 Active Support,现在您可以只获取您需要的部分.我似乎记得这个东西在 activesupport/duration
中.我相信还有其他一些宝石也可以帮助处理时间.
Which will do the right thing is d
is a DateTime
or a Time
. You can use Active Support on its own, and these days you can pull in just the bits you need. I seem to recall that this stuff is in activesupport/duration
. I believe there are a few other gems that offer help with time handling too.
这篇关于ruby 中的时间操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!