keruilin
keruilin

Reputation: 17552

How to add minutes to a Time object

In Ruby, how do I do Time.now + 10.hours?

Is there an equivalent for secs and mins? For example:

Time.now + 15.mins

Upvotes: 87

Views: 102817

Answers (6)

Bonnie Simon
Bonnie Simon

Reputation: 61

There is an advance function in Active Support refer.

You can do the following using advance:

d = DateTime.new(2010, 2, 28, 23, 59, 59) 
=> Sun, 28 Feb 2010 23:59:59 +0000
d.advance(hours: 1) 
=> Mon, 01 Mar 2010 00:59:59 +0000

Upvotes: 1

Sushant
Sushant

Reputation: 427

Time Object

time = Time.now

Adding minutes to a time object:

time + 5.minutes

Upvotes: 2

Gishu
Gishu

Reputation: 136683

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

See the Active Support Core Extensions for Date, DateTime and Time for more information.

Upvotes: 2

mahi-man
mahi-man

Reputation: 4696

Also in ActiveSupport you can do:

10.minutes.from_now

10.minutes.ago

Upvotes: 24

Phrogz
Phrogz

Reputation: 303520

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

Upvotes: 162

twe4ked
twe4ked

Reputation: 2902

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

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

Upvotes: 83

Related Questions