How to handle non-English dates using the DateTime strptime parameter in Ruby?

I am trying to parse dates exported from CMS. Unfortunately, with the Swedish language set. The names of the months are reduced to three characters, which matters when it comes to the months of May and October (“May” versus “May” and “Oct” versus “Oct”).

I would expect to use DateTime.strptime with the correct set of locales to solve this problem, for example:

require 'locale' Locale.default = "sv_SE" require 'date' DateTime.strptime("10 okt 2009 04:32",'%d %b %Y %H:%M') 

However, the date is still being parsed as the abbreviated month names will be used in English:

 ArgumentError: invalid date from lib/ruby/1.9.1/date.rb:1691:in `new_by_frags' from lib/ruby/1.9.1/date.rb:1716:in `strptime' from (irb):9 from bin/irb:16:in `<main>' 

Question 4339399 relates to the same subject and links to a comprehensive solution to fix this.

Is there a more elegant solution? Is this even considered a bug in Ruby?

+6
source share
1 answer

Honestly, since you only have two months that are different, I would probably just gsub them:

 DateTime.strptime("10 okt 2009 04:32".gsub(/okt/,'Oct'),'%d %b %Y %H:%M') 

If you want, you can put this in a little helper:

 def swedish_to_english_date(date_string) date_string.gsub(/may|okt/, 'may' => 'May', 'okt' => 'Oct') end DateTime.strptime(swedish_to_english_date("10 okt 2009 04:32"),'%d %b %Y %H:%M') #=> #<DateTime: 110480161/45,0,2299161> 

Edit: note that gsub with a hash as the second argument is thing 1.9, in 1.8 you can do something like

 >> months = { 'may' => 'May', 'okt' => 'Oct' } => {"okt"=>"Oct", "may"=>"May"} >> "may okt".gsub(/may|okt/) { |match| months[match] } => "May Oct" 
+4
source

Source: https://habr.com/ru/post/898187/


All Articles