如何在Ruby中解析缩写日期?

时间:2014-02-11 16:09:30

标签: ruby-on-rails ruby date

我在Rails 4.0.2应用程序中使用Ruby 2.1。我需要将一个字符串转换为一个有效的Date对象,但我尝试的一切都说它是一个无效的日期:

# in irb
date = 'Feb 9'
Date.strptime(date, '%m %-d')
# NoMethodError: undefined method `strptime' for Date:Class

# in Rails console
date = 'Feb 9'
Date.strptime(date, '%m %-d')
# ArgumentError: invalid date
#   from (irb):2:in `strptime'

date += ' ' + Time.now.year.to_s
Date.strptime(date, '%m %-d %Y')
# ArgumentError: invalid date

如何以这种缩写格式解析日期?

3 个答案:

答案 0 :(得分:4)

“Feb”不是有效的月份数。

[1] pry(main)> date = 'Feb 9'
"Feb 9"
[2] pry(main)> Date.strptime(date, "%b %d")
Sun, 09 Feb 2014

如,

%m - Month of the year, zero-padded (01..12)
        %_m  blank-padded ( 1..12)
        %-m  no-padded (1..12)
%B - The full month name (``January'')
        %^B  uppercased (``JANUARY'')
%b - The abbreviated month name (``Jan'')
        %^b  uppercased (``JAN'')
%h - Equivalent to %b

答案 1 :(得分:2)

格式字符串错误,应该是:

require 'date'
date = 'Feb 9'
Date.strptime(date, '%b %d').to_s
# => "2014-02-09"

%m将匹配月份编号(1-12),而%b根据当前区域设置匹配缩写的月份名称。正如Ruby documentation所述,可用格式记录在strptime(3)手册页中。

或使用Date.parse方法:

Date.parse(date).to_s
# => "2014-02-09"

更新:我之前没有注意到,-修饰符与未填充的日期数字符号strptime匹配:

Date.strptime('9', '%-d').to_s
# ArgumentError: invalid date

Date.strptime('9', '%d').to_s
# => "2014-02-09"

答案 2 :(得分:1)

您可以直接解析日期:

date = 'Feb 9'

Date.parse date