Forum: Ruby on Rails Date parsing issues

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Dec M. (Guest)
on 2009-04-22 12:21

I'm having problem at the moment trying to parse a date. I'm reading in
2 dates from the view and want to search a DB for records between the 2

The 2 dates I read are in the format '%d.%m.%Y', e.g. 22.04.2009
The dates in the DB are stored as VARCHAR in the format '%Y/%m/%d

I've set the default date in environments.db as follows:
    :default => '%d.%m.%Y'

I've tried parsing the 2 dates as follows:

However the result is incorrect for my locale.
If I read in a date '12.04.2009' I would get the following output:
2009/12/04, when what I want is 2009/04/12. It's getting the day and
month mixed. The Locale on my machine is correct and the timezone in the
environments.db is set to UTC.
Dmitry S. (Guest)
on 2009-04-22 13:24
(Received via mailing list)

All setting you've set affect only date formatting but not parsing.
And unfortunately it seems that there are no clean way to parse
DD.MM.YYYY dates in Ruby. But there is a dirty way:

# put it in some initializer
class << Date
  alias _parse_without_eu_format _parse
  def _parse(str, comp = false)
    str = str.to_s
    str = "#{$3}-#{$2}-#{$1}" if /(\d{2})\.(\d{2})\.(\d{4})/ =~ str
    _parse_without_eu_format(str, comp)

class << Date
  def try_parse(string, default = nil)
    components = ParseDate.parsedate(string)
    components.first ? new(*components[0..2]) : default

# then the dates will be parsed correctly
p Date.parse("22.04.2009")
p Date.parse("04/22/2009")

Dec M. (Guest)
on 2009-04-23 16:47
Thanks Dmitry!
I was getting a little confused with the date formatting and parsing.
This topic is locked and can not be replied to.