How do I parse a translated date in Ruby on Rails?

谁都会走 提交于 2021-02-08 04:51:36

问题


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?


回答1:


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



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/12064029/how-do-i-parse-a-translated-date-in-ruby-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!