Hi,
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
dates.
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
%H:%M:%S''
I''ve set the default date in environments.db as follows:
ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!(
:default => ''%d.%m.%Y''
)
I''ve tried parsing the 2 dates as follows:
Time.parse(params[:from]).strftime("%Y/%m/%d")
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.
--
Posted via http://www.ruby-forum.com/.
Declan,
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)
end
end
class << Date
def try_parse(string, default = nil)
components = ParseDate.parsedate(string)
components.first ? new(*components[0..2]) : default
end
end
# then the dates will be parsed correctly
p Date.parse("22.04.2009")
p Date.parse("04/22/2009")
Dmitry