Caffeine-Powered Life

Date.parse_us

Ruby 1.9+ is going to use international date formats (dd-mm-yyyy), and there’s not a damned thing you can do about it. So let’s do something about it. While you can easily output a date in any format you can imagine, have a date as input is a bit more tricky.


class Date

  def self.parse_us(value)

    if value =~ /(\d{1,2}).(\d{1,2}).(\d{4})/

      # puts "#{$3}-#{$1}-#{$2}"      

      Date.civil($3.to_i, $1.to_i, $2.to_i)      

    else

      # Unrecognized format. Just return the original value.

      value      

    end

  end

end



irb(main):001:0> Date.parse("01/06/2011")

=> Wed, 01 Jun 2011

irb(main):002:0> Date.parse_us("01/06/2011")

=> Thu, 06 Jan 2011

Comments