Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I add N days to time T (accounting for Daylight Savings Time)?

Tags:

time

ruby

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.

like image 203
fearless_fool Avatar asked Jan 31 '13 09:01

fearless_fool


2 Answers

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
like image 160
Sergio Tulentsev Avatar answered Oct 21 '22 08:10

Sergio Tulentsev


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 
like image 44
user1385729 Avatar answered Oct 21 '22 08:10

user1385729