Remaining days : Date Calculation « Date « Ruby






Remaining days


require 'date'
def remaining(date, event)
  intervals = [["day", 1], ["hour", 24], ["minute", 60], ["second", 60]]
  elapsed = DateTime.now - date
  tense = elapsed > 0 ? "since" : "until"
  interval = 1.0
  parts = intervals.collect do |name, new_interval|
    interval /= new_interval
    number, elapsed = elapsed.abs.divmod(interval)
  "#{number.to_i} #{name}#{"s" unless number == 1}"
  end
  puts "#{parts.join(", ")} #{tense} #{event}."
end

remaining(DateTime.new(2006, 4, 15, 0, 0, 0, DateTime.now.offset),"the book deadline")

 








Related examples in the same category

1.Subtract 61 days from a date:
2.Add and subtract six months using the >> and << methods.
3.Doing Date Arithmetic
4.Doing DateTime Arithmetic
5.Minus one DateTime from another
6.Move DateTime
7.leap year day
8.Counting the Days Since an Arbitrary Date
9.advent calendar
10.Minus DateTime by day