Home » Ruby » Add minutes to Time object

Add minutes to Time object

Posted by: admin November 30, 2017 Leave a comment

Questions:

So in ruby you can do Time.now + 10.hours…

There isn’t an equivalent for secs and mins? For ex, Time.now + 15.mins.

Answers:

Ruby (the programming language) doesn’t have 10.hours, that’s ActiveSupport as part of Ruby on Rails (the web framework). And yes, it does have both minutes and seconds methods.

However, Time#+ (the + method on Time instances) returns a new Time instance that is that many seconds in the future. So without any Ruby on Rails sugar, you can simply do:

irb> t = Time.now
#=> 2011-08-03 22:35:01 -0600

irb> t2 = t + 10               # 10 Seconds
#=> 2011-08-03 22:35:11 -0600

irb> t3 = t + 10*60            # 10 minutes
#=> 2011-08-03 22:45:01 -0600

irb> t4 = t + 10*60*60         # 10 hours
#=> 2011-08-04 08:35:01 -0600

Questions:
Answers:

If you are using ActiveSupport, what you are looking for is the full .minutes and .seconds.

Time.now + 10.minutes
Time.now + 10.seconds

Questions:
Answers:

Also in ActiveSupport you can do:

10.minutes.from_now

10.minutes.ago

Questions:
Answers:

I think you’re talking about extensions added by Rails. I think you need 15.minutes

See docs here