Class: Date

Inherits:
Object show all
Defined in:
lib/webget_ruby_ramp/date.rb

Overview

Date extensions

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.between(min, max) ⇒ Date

Returns a random date between min & max.

Examples:

d1= Date.parse('2008-01-01')
d2= Date.parse('2009-01-01')
Date.between(d1,d3) => Date 2008-11-22

Returns:

  • (Date)

    a random date between min & max



40
41
42
# File 'lib/webget_ruby_ramp/date.rb', line 40

def self.between(min,max)
  min+rand(max-min)
end

Instance Method Details

#age_days(compare_date = Date.today) ⇒ Integer

Returns the age in days for a given date.

Returns:

  • (Integer)

    the age in days for a given date.



87
88
89
90
# File 'lib/webget_ruby_ramp/date.rb', line 87

def age_days(compare_date=Date.today)
  (compare_date.is_a? Date) or raise ArgumentError, "compare_date must be a date"
  (compare_date-self).to_i
end

#age_years(compare_date = Date.today) ⇒ Integer

Returns the age in years for a given date.

Examples:


birthdate=Date.new(1980,10,31)
birthdate.age_years => 28 (where 28 is the correct age for today)

of custom dates


birthdate=Date.new(1980,10,31)

valentines = Date.new(2008,02,14)
birthdate.age_years(valentines) => 27  # before the birthday

halloween = Date.new(2008,10,31)
birthdate.age_years(halloween) => 28   # on the birthday

new_years_eve = Date.new(2008,12,31)
birthdate.age_years(new_years_eve) => 28  # after the birthday

Returns:

  • (Integer)

    the age in years for a given date.



76
77
78
79
80
81
82
# File 'lib/webget_ruby_ramp/date.rb', line 76

def age_years(compare_date=Date.today)
  (compare_date.is_a? Date) or raise ArgumentError, "compare_date must be a date"
  age=compare_date.year-year
  compare_month = compare_date.month
  age-=1 if compare_month < month or (compare_month==month and compare_date.day < day)
  age
end

#to_sqlString

Returns date in a sql format: YYYY-MM-DD.

Examples:

d=Date.today
d.to_sql => "2007-12-31"

Returns:

  • (String)

    date in a sql format: YYYY-MM-DD



51
52
53
# File 'lib/webget_ruby_ramp/date.rb', line 51

def to_sql
  return sprintf("%04d-%02d-%02d",year,month,mday)
end

#weekday?Boolean

Returns true if the date is a weekday: Mon, Tue, Wed, Thu, Fri.

Examples:

d = Date.parse('2008-01-01')
d.wday => 2
d.weekday? => true

Returns:

  • (Boolean)

    true if the date is a weekday: Mon, Tue, Wed, Thu, Fri



16
17
18
# File 'lib/webget_ruby_ramp/date.rb', line 16

def weekday?
  wday>0 and wday<6
end

#weekend?Boolean

Returns true if the date is a weekend: Sat, Sun.

Examples:

d = Date.parse('2008-01-05')
d.wday => 6
d.weekend? => true

Returns:

  • (Boolean)

    true if the date is a weekend: Sat, Sun



28
29
30
# File 'lib/webget_ruby_ramp/date.rb', line 28

def weekend?
  wday==0 or wday==6
end