我的字符串是:"02-19-2016"
,是MM-DD-YYYY格式的日期。它为某些场景提供了适当的结果,但对于某些场景,它失败了:
@query="02-19-2016"
d, m, y = @query.split '-'
# => ["02", "19", "2016"]
Date.valid_date? y.to_i, m.to_i, d.to_i
# => false
有人可以提供任何解决方案吗?
答案 0 :(得分:2)
更改
d, m, y = @query.split '-'
到
m, d, y = @query.split '-'
答案 1 :(得分:2)
Date.strptime
以按特定模式解析字符串:
require 'date'
Date.strptime("02-19-2016", '%m-%d-%Y')
#<Date: 2016-02-19 ((2457438j,0s,0n),+0s,2299161j)>
答案 2 :(得分:0)
require 'date'
m, d, y = '02-19-2016'.split('-').map(&:to_i)
# => [2, 19, 2016]
Date.valid_date? y, m, d
# => true
date = Date.civil(y, m, d)
# => #<Date: 2016-02-19 ((2457438j,0s,0n),+0s,2299161j)>