I have a Time object T. What's a reasonable way to add N days to T?
The best I've come up with feels somewhat tortured:
require 'date'
def add_days(time, days)
time.to_date.next_day(days).to_time
end
P.S.: If you are in the US, a correct answer must satisfy:
add_days(Time.new(2013, 3, 10, 0), 1) == Time.new(2013, 3, 11, 0)
and if you are in the EU, a correct answer must satisfy:
add_days(Time.new(2013, 3, 31, 0), 1) == Time.new(2013, 4, 1, 0)
P.P.S: This is a Ruby question, not a Rails question.
Time
has a +
method which accepts seconds.
N = 3
t = Time.now + N * 86400 # 24 * 60 * 60
Or, if you bring ActiveSupport in, it's easier
require 'active_support/core_ext'
t = Time.now + N.days
You can obviously make your own helper
class Fixnum
def days
self * 86400
end
end
t = Time.now # => 2013-01-31 16:06:31 +0700
t + 3.days # => 2013-02-03 16:06:31 +0700
ActiveSupport::TimeWithZone seems to handle this well
> t1 = ActiveSupport::TimeZone['Eastern Time (US & Canada)'].parse('2013-03-10')
=> Sun, 10 Mar 2013 00:00:00 EST -05:00
Notice the class type below:
> t1.class
=> ActiveSupport::TimeWithZone
Notice the change from EST above to EDT below:
> t1 + 1.day
=> Mon, 11 Mar 2013 00:00:00 EDT -04:00
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With