A little Ruby library for working with months.
$ gem install month
You can create a new Month object with a year and month number:
Month.new(2014,1)# January 2014Alternatively you can use the Month method to cast various date/time objects to Month objects:
Month(Date.new(2014,1,31))# January 2014Month(Time.at(1234567890))# February 2009The method will idempotently return Month objects as-is:
Month(Month.new(2014,1))# January 2014, same objectUse the Month.parse method to parse a YYYY-MM formatted string:
Month.parse('2014-01')# January 2014The #year attribute will return the year of the month:
Month.new(2014,1).year# 2014The #number attribute will return the number of the month:
Month.new(2014,1).number# 1The #name method will return the name of the month as a symbol:
Month.new(2014,1).name# :JanuaryAlternatively you can use predicate methods to test for a given month:
Month.new(2014,1).january?# trueMonth.new(2014,2).january?# falseThe #to_s method will return a YYYY-MM formatted string representation of the month:
Month.new(2014,1).to_s# "2014-01"You can add/subtract an integer number of months:
Month.new(2014,1) + 1# February 2014Month.new(2014,1) - 1# December 2013The #step method iterates between 2 months, similar to Date#step:
Month.new(2014,1).step(Month.new(2014,12))do |month|
...
endThe #include? method can be used to test if the month includes a date:
Month.new(2014,1).include?(Date.new(2014,1,31))# trueThe #dates method returns a range containing the dates in the month:
Month.new(2014,1).dates# Range containing 31 Date objectsThe #length method returns the number of days in the month:
Month.new(2014,1).length# 31Month objects can be used in case expressions.
Month objects can be used as hash keys.
Month objects can be used in ranges.
Month objects are comparable.
The Month::Methods module provides methods for constructing Month objects and Date objects in a manner that closely resembles written english:
includeMonth::Methodsmonth=January2014date=January15,2014It is not included globally by default; you can either include it within your own modules/classes or globally within your own application/script.
This current implementation is an accidental rewrite of an older library/gem with the same name/purpose (fhwang / month). Thanks to Francis for kindly allowing me to re-use the same gem name.