本文介绍了Ruby 错误地解析了 2 位数年份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Ruby 正确解析第一个日期,但第二个不正确.使用 ruby​​ 1.9.3 和 2.1.2 进行测试.

Ruby correctly parses the first date but the second one is incorrect. Tested with ruby 1.9.3 and 2.1.2.

知道如何让它始终如一地工作吗?(我们将出生日期设为 2 位数年份)

Any idea how to get it to work consistently? (We are getting in birth dates as 2 digit years)

Date.strptime("10/11/89","%d/%m/%y")
=> Fri, 10 Nov 1989

Date.strptime("15/10/63","%d/%m/%y")
=> Mon, 15 Oct 2063

推荐答案

strptime 方法将文本63"解析为 2063 年,而不是您想要的 1963 年.
这是因为该方法使用POSIX标准.

The strptime method is parsing the text "63" to the year 2063, not 1963 as you want.
This is because the method decides the century by using the POSIX standard.

chronic gem 也有类似的问题,因为它决定了世纪,尽管有所不同.

The chronic gem has a similar issue because it decides the century, though differently.

解决办法是调整日期:

d = Date.strptime("15/10/63","%d/%m/%y")
if d > Date.today
  d = Date.new(d.year - 100, d.month, d.mday)
end

在这篇文章的评论中,Stefan 推荐了一个好的班轮:

In the comments of this post, Stefan suggests a good one liner:

d = d.prev_year(100) if d > Date.today

如果你需要速度,你可以尝试这样优化:

If you need speed, you can try optimizing like this:

d <= Date.today || d = d << 1200

这篇关于Ruby 错误地解析了 2 位数年份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!