2011-09-28 35 views
6

我想解析从CMS导出的日期。不幸的是,瑞典语区域设置。月份名称缩写为三个字符,它们在五月和十月(“maj”与“May”以及“okt”与“Oct”)月份有所不同。如何使用Ruby中的DateTime strptime解析非英语日期?

我希望用DateTime.strptime用正确的区域设置来解决这个问题,就像这样:

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

的日期仍然然而解析为它在英语中会使用月份的缩写:

关于同一问题并链接到用于固定该络合物溶液
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触摸。

有没有更优雅的解决方案呢?这甚至被认为是Ruby中的一个错误?

回答

4

说实话,因为你只能有两个月的时间是不同的,我可能只是gsub他们:

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

如果你愿意,你可以将它放入一个小帮手:

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> 

编辑:请注意,gsub利用哈希作为第二个参数是1.9的事情,你1.8可以这样做

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

看起来像是一个合理的解决方案。我有这样的东西,但不知道你可以使用'gsub'这样的。比两个'gsub'之后的链条更可读。 – moonhouse

+0

所以没有办法与l10n做到这一点?只是容易出错的gsubs? – nurettin

+0

这个特殊情况下的'gsub'对我来说并不特别容易出错。根据你的使用情况,它可能是。 –