Skip to content

Instantly share code, notes, and snippets.

@mgreenly
Created February 20, 2012 20:34
Show Gist options
  • Save mgreenly/1871238 to your computer and use it in GitHub Desktop.
Save mgreenly/1871238 to your computer and use it in GitHub Desktop.
Extending Date parsing in Ruby 1.9.3
require 'date'
class Date
class << self
def convert_date_string(input)
# mm-dd-yyyy
if input =~ /^(\d{1,2})[^\d\w\s](\d{1,2})[^\d\w\s](\d{4})([T|\W].*)?/
"%0.4d/%0.2d/%0.2d#{$4}" % [$3, $1, $2].map(&:to_i)
# mm-dd-yy
elsif input =~ /^(\d{1,2})[^\d\w\s](\d{1,2})[^\d\w\s](\d{1,2})([T|\W].*)?/
"%0.4d/%0.2d/%0.2d#{$4}" % ["#{today.century}#{$3}", $1, $2].map(&:to_i)
# mm-dd
elsif input =~ /^(\d{1,2})[^\d\w\s](\d{1,2})([T\W].*)?/i
"%0.4d/%0.2d/%0.2d#{$3}" % [today.year, $1, $2].map(&:to_i)
# 28/Jan
elsif input =~ /^(\d+)[^\w\d]((jan)|(feb)|(mar)|(apr)|(may)|(jun)|(jul)|(aug)|(sep)|(oct)|(nov)|(dec))(\s.*)?/i
"#{$1}/#{$2}#{$3}"
else
input
end
end
alias _original_parse _parse
def _parse(input, comp=true)
_original_parse(convert_date_string(input), comp)
end
alias original_parse parse
def parse(input, comp=true)
original_parse(convert_date_string(input), comp)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment