Reputation: 13635
Is it possible to parse a localized DateTime string back to a proper DateTime using native Ruby or Rails methods?
I looked in i18n where I would expect this to be, since it holds the formats and locale, but I couldn't find it.
I have a String: "za 18 mei 18:05"
which is Dutch (:nl
), in English it would be "Sa 18 May 6:15PM"
.The dateformat is: "%a %d %b %H:%M"
. I want the String to parse back to 2012-05-08T18:12:00+01:00
.
Is there a possible way to get a DateTime from this? I have a large locale file for my Dutch translations and I can't imagine I cannot use this to parse a format back to db format
Upvotes: 2
Views: 1712
Reputation: 622
You can also take a look at https://github.com/carlosantoniodasilva/i18n_alchemy it works in a similar fashion to delocalize but its scope is limited to models so it does not mess with the view classes.
Upvotes: 0
Reputation: 7810
You will need to manipulate your date strings a little bit, because they are not in English.
Try this:
nl = "vri 18 mei 18:05"
dt = DateTime.strptime(nl.gsub(/vri|mei/, 'vri' => 'Fri', 'mei' => 'May'), "%a %d %b %H:%S")
That is an example approach on how to replace 'za' with 'Sat' and 'mei' with 'May' before sending the string to strptime
. You probably need to come up with a more elegant approach on replacing your original strings (writing a helper for example).
Using the delocalize
gem
Alternatively, maybe you can try the gem delocalize
:
I18n.locale = :nl
Delocalize::LocalizedDateTimeParser.parse("Vri 18 mei 18:02", DateTime)
Make sure that you have the correct "nl.yml" in your config/locales
folder.
You can grab from here: https://github.com/svenfuchs/rails-i18n/blob/master/rails/locale/nl.yml
Upvotes: 2