Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse Italian Date with Ruby

Tags:

date

parsing

ruby

I would like to use Date.parse, but it doesn't work with Italian month names!

Date.parse "26 agosto 1991" => Sun, 26 Jul 2009

Is there any alternative?

like image 842
collimarco Avatar asked Feb 27 '26 04:02

collimarco


2 Answers

All I can come up with is about the same schnaader's idea: make a mapping between MONTHNAMES, etc. and then loop through the mapping, doing gsub. That is:

english_to_italian = {
  'english' => 'italian',
  ...
  'august' => 'agosto',
  ...
}

english_to_italian.each do |en, it|
  date_string.gsub!(/\b#{en}\b/i, it)
end

date = Date.parse(date_string)

The Date.italy (same as Date::ITALY, I think) method is worth pointing out, just in case there are calendar differences that I'm not aware of.

Really, I'm surprised I couldn't find a general solution for this. Maybe there are some i18n modules for Rails that might do it?

UPDATE: This might get you closer, but it doesn't look like it would do everything: http://github.com/rafaelrosafu/i18n_localize_core/tree/master

like image 159
Benjamin Oakes Avatar answered Feb 28 '26 22:02

Benjamin Oakes


Well, you could use string replacement routines or RegEx to convert the month into the english translation and call Date.parse after that. After all, you only have to replace 12 possible values, or are there more complex strings, too?

Note that there are different things in the Date class that could help you here, for example the constants MONTHNAMES and ABBR_MONTHNAMES that contain the English month names and their abbrevations.

Simple example code just to show what I mean:

# Note that you perhaps might want to
# convert input strings to lowercase
myString = "26 agosto 1991" 

# replace italian month names
myString.gsub("...", "januar")
...
myString.gsub("agosto", "august")
...
myString.gsub("...", "december")

# now it should parse correctly
Date.parse(myString)
like image 40
schnaader Avatar answered Feb 28 '26 20:02

schnaader



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!