Ruby/Time/Time Calculation

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Содержание

Add seconds and multiples of seconds to add to a time with +

stop = Time.local( 2007, "jan", 30, 1, 15, 20 )
stop.inspect 
# Add a minute (60 seconds)
stop + 60 
# Add an hour (60*60)
stop + 60*60 
# Add three hours (60*60*3)
stop + 60*60*3 
# Add a day (60*60*24)
stop + 60*60*24



Doing Time Arithmetic

day_one = Time.gm(1999, 12, 31)
day_two = Time.gm(2000, 1, 1)
day_two - day_one                           # => 86400.0
day_one - day_two                           # => -86400.0



Finding the Day of the Week

def every_sunday(d1, d2)
  one_day = d1.is_a?(Time) ? 60*60*24 : 1
  sunday = d1 + ((7-d1.wday) % 7) * one_day
  while sunday < d2
    yield sunday
    sunday += one_day * 7
  end
end
def print_every_sunday(d1, d2)
  every_sunday(d1, d2) { |sunday| puts sunday.strftime("%x")}
end
print_every_sunday(Time.local(2006, 1, 1), Time.local(2006, 2, 4))



Is it a leap year

class Time
  def Time.leap? year
    if year % 400 == 0
      true
    elsif year % 100 == 0
      false
    elsif year % 4 == 0
      true
    else
      false
  end
end



You can see the difference in two Time objects by subtracting them:

stop = Time.local( 2007, "jan", 30, 1, 15, 20 )
start = Time.local( 2008, "jan", 30, 1, 15, 20 )
puts stop - start