Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 parse a date in a different language

I have a text_field :birthday_line in my user form, that I need to parse into the user's birthday attribute. So I'm doing something like this in my User class.

attr_accessor :birthday_line
before_save :set_birthday

def set_birthday
  self.birthday = Date.strptime(birthday_line, I18n.translate("date.formats.default")
end

But the problem is that for some reason it gives me an error saying Invalid date when I try to pass in a string 27 января 1987 г. wich should be parsed to 1987-01-27. The format and month names in my config/locales/ru.yml

ru:
  date:
    formats:
      default: "%d %B %Y г."
    month_names: [~, января, февраля, марта, апреля, мая, июня, июля, августа, сентября, октября, ноября, декабря]

seem to be correct.

Date.parse also doesn't help, it just parses the day number (27) and puts the month and year to todays date (so it'll be September 27 2013 instead of January 27 1987).

like image 630
Almaron Avatar asked Sep 12 '13 12:09

Almaron


1 Answers

I had the same problem and what I can suggest:

string_with_cyrillic_date = '27 Января 1987'

1)create array of arrays like this

months = [["января", "Jan"], ["февраля", "Feb"], ["марта", "Mar"], ["апреля", "Apr"], ["мая", "May"], ["июня", "Jun"], ["июля", "Jul"], ["августа", "Aug"], ["сентября", "Sep"], ["октября", "Oct"], ["ноября", "Nov"], ["декабря", "Dec"]]

2) Now you can iterate this and find your cyrillic month:

months.each do |cyrillic_month, latin_month|
  if string_with_cyrillic_date.match cyrillic_month      
    DateTime.parse string_with_cyrillic_date.gsub!(/#{cyrillic_month}/, latin_month) 
  end
end

And now you will receive the date that you expect

27 Jan 1987
like image 83
mmike Avatar answered Sep 22 '22 20:09

mmike