arr = ["24/Oct/2014:13:43:15 -0600",
"05/Oct/2014:14:47:25 -0600",
"24/Oct/2014:13:46:15 -0600"]
如果你确定日期字符串的格式是正确的,并且代表有效的日期,你可以简单地写
arr.map { |s| s[0,11] }
#=> ["24/Oct/2014", "05/Oct/2014", "24/Oct/2014"]
另一方面,如果您希望检查日期字符串的有效性,您可能希望将每个日期字符串转换为日期对象,然后将该对象转换为所需的字符串格式。这样,如果日期字符串无效,则会引发异常。
require 'date'
arr.map { |s| DateTime.strptime(s, '%d/%b/%Y:%H:%M:%S %z').strftime('%d/%b/%Y') }
#=> ["24/Oct/2014", "05/Oct/2014", "24/Oct/2014"]
这使用方法DateTime::strptime 和DateTime#strftime。 strftime 的文档中解释了日期格式字符串。
假设
arr = ["42/Oct/2014:13:43:15 -0600"]
然后
arr.map { |s| DateTime.strptime(s, '%d/%b/%Y:%H:%M:%S %z').strftime('%d/%b/%Y') }
#=> ArgumentError: invalid date
您可以改用DateTime::parse 而不是strptime 将日期字符串转换为Date 对象,但它在识别无效日期方面非常薄弱。例如:
DateTime.parse "123456/01-02abc"
#=> #<DateTime: 123456-01-02T00:00:00+00:00 ((46812439j,0s,0n),...
DateTime.parse "-7/8"
#=> #<DateTime: 2016-07-08T00:00:00+00:00 ((2457578j,0s,0n),...
DateTime.parse "He demanded 1/2 of the pie"
#=> #<DateTime: 2016-01-02T00:00:00+00:00 ((2457390j,0s,0n),...