Reputation: 18064
I have configured an application in Ruby on Rails with translations to Spanish.
Now I need to parse a translated date, for example:
Jueves, 22 de Noviembre del 2012
I'm trying to do it this way:
Date.strptime('Jueves, 22 de Noviembre, 2012', '%A, %e de %B, %Y')
But it throws an invalid date
error.
How can I do it?
Upvotes: 3
Views: 1248
Reputation: 303
I had a very similar problem and I wrote a gem specifically for the purpose of parsing any non-English textual dates (that use Gregorian calendar), it's called Quando. The gem readme is very informative and has code examples, but in short, this is how it works:
require 'quando'
Quando.configure do |c|
# First, tell the library how to identify Spanish months in your dates:
c.jan = /enero/i
c.feb = /febrero/i
c.mar = /marzo/i
c.apr = /abril/i
c.may = /mayo/i
c.jun = /junio/i
c.jul = /julio/i
c.aug = /agosto/i
c.sep = /septiembre/i
c.oct = /octubre/i
c.nov = /noviembre/i
c.dec = /diciembre/i
# Then, define pattern matchers for different date variations that you need to parse.
# c.day is a predefined regexp that matches numbers from 1 to 31;
# c.month_txt is a regexp that combines all month names that you previously defined;
# c.year is a predefined regexp that matches 4-digit numbers;
# c.dlm matches date parts separators, like . , - / etc. See readme for more information.
c.formats = [
/#{c.day} \s #{c.month_txt} ,\s #{c.year} $/xi, # matches "22 Mayo, 2012" or similar
/#{c.year} - #{c.month_txt} - #{c.day}/xi, # matches "2012-Mayo-22" or similar
# Add more matchers as needed. The higher in the order take preference.
]
end
# Then parse the date:
Quando.parse('Jueves, 22 Noviembre, 2012') # => #<Date: 2012-11-22 …>
You can redefine the matchers for date parts and formats partially or entirely, both globally or just for a single parser instance (to preserve your global settings), and use all the power of regular expressions. There are more examples in the readme and in the source code. Hope you'll find the library useful.
Upvotes: 2
Reputation: 18064
So, the answer is: it's not possible, at least right now.
The only way to have it working, is by using javascript on the client side, and convert the format to another one before sending the field to the server. Then Rails will not have any problem parsing it.
Upvotes: -1
Reputation: 7490
Date::parse
should understand Spanish. However, that de
seems to throw the parser off. If you could get it into this format, this will work
Date.parse "Jueves, 22 Noviembre, 2012"
=> Thu, 22 Nov 2012
Upvotes: 6