Time manipulation in ruby

2019-03-14 11:16发布

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?

标签: ruby time
3条回答
乱世女痞
2楼-- · 2019-03-14 11:47

Assuming you have required ActiveSupport or you're working in a Rails project. A very simple an readable way to do this in ruby is:

DateTime + 5.minutes
Time + 5.minutes

Also works with .seconds, .hours, .days, .weeks, .month, .years

查看更多
叛逆
3楼-- · 2019-03-14 11:47

Just use the active support time extensions. They are very convenient and less error prone than trying to do this by hand. You can import just the module you need:

# gem 'activesupport'
require 'active_support/core_ext/numeric/time.rb'
DateTime.now + 20.minutes

N.B: Yes, this goes against the StackOverflow party line of staying away from 3rd party libraries, but you shouldn't avoid using libraries when they are practically standard, reduce your risk significantly, and provide better code clarity.

查看更多
啃猪蹄的小仙女
4楼-- · 2019-03-14 11:57

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)

Will add 10 seconds to d (since there are 86400 seconds in a day).

If you are using Rails, ActiveSupport adds some helper methods and you can do

d + 20.minutes + 10.seconds

Which will do the right thing is d is a DateTime or a Time. You can use ActiveSupport 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.

查看更多
登录 后发表回答