Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Try'n'Go: The Last Date (See related posts)

Extends Date class with a method that return the last Date of a month.
Date#last_of_month takes either a Fixnum or a Time as argument.

   1  
   2  require 'date'
   3  
   4  class Date
   5    def self.last_of_month( arg = Time.now )
   6      year = ( arg.is_a? Fixnum ) ? Time.now.year : arg.year
   7      mon  = ( arg.is_a? Fixnum ) ? arg : ( arg.mon rescue Time.now.mon )
   8      
   9      raise ArgumentError unless mon.between?( 1, 12 )
  10  
  11      begin; Date.new year, mon, mday ||= 31
  12      rescue ArgumentError; mday -= 1; retry
  13      end
  14    end
  15  end

You need to create an account or log in to post comments to this site.


Click here to browse all 5545 code snippets

Related Posts