Class | Date |
In: |
lib/more/facets/date.rb
|
Parent: | Object |
This new version of Date extension has been largely improved by porting some of the methods used by ActiveSupport. The old version already had much in common with the Active Support library, so it was decided to take it a step further in that direction for the sake of interoparability.
Hopefully most of these methods will find there way into Ruby‘s own standard library eventually.
The biggest difference with ActiveSupport is the lack of many of the "English-esque" methods, and that we use stamp with Date::FORMAT, instead of to_formmated_s with Date::DATE_FORMATS. We do not override the standard to_s method like ActiveSupport does.
FORMAT | = | { :short => "%e %b", :long => "%B %e, %Y", :db => "%Y-%m-%d", :number => "%Y%m%d", :rfc822 => "%e %b %Y", :default => "%Y-%m-%d", nil => "%Y-%m-%d" |
Provides precise Date calculations for years, months, and days. The options parameter takes a hash with any of these keys: :years, :months, :weeks, :days.
Returns a new Date where one or more of the elements have been changed according to the options parameter.
Examples:
Date.new(2007, 5, 12).change(:day => 1) # => Date.new(2007, 5, 1) Date.new(2007, 5, 12).change(:year => 2005, :month => 1) # => Date.new(2005, 1, 12)
Returns the number of days in the date‘s month.
Date.new(2004,2).days_in_month #=> 28
CREDIT: Ken Kunz.
Convert to a formatted string. See DATE_FORMATS for predefined formats.
This method is aliased to to_s.
date = Date.new(2007, 11, 10) # => Sat, 10 Nov 2007 date.stamp(:db) # => "2007-11-10" date.stamp(:short) # => "10 Nov" date.stamp(:long) # => "November 10, 2007" date.stamp(:rfc822) # => "10 Nov 2007"
You can add your own formats to the Date::FORMAT hash. Use the format name as the hash key and a strftime string as the value. Eg.
Date::FORMAT[:month_and_year] = "%B %Y"
Converts a Date instance to a Time, where the time is set to the beginning of the day. The timezone can be either :local or :utc (default :local).
date = Date.new(2007, 11, 10) # => Sat, 10 Nov 2007 date.to_time # => Sat Nov 10 00:00:00 0800 2007 date.to_time(:local) # => Sat Nov 10 00:00:00 0800 2007 date.to_time(:utc) # => Sat Nov 10 00:00:00 UTC 2007