Ruby incorrectly parses 2-digit year

Ruby parses the first number correctly, but the second is incorrect. Tested with rubies 1.9.3 and 2.1.2.

Any idea how to make it work consistently? (We get 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 
+6
source share
3 answers

The strptime method processes the text "63" until 2063, not 1963, as you want. This is because the method solves the century using the POSIX standard .

The chronic gem has a similar problem because it solves the century, albeit in different ways.

The solution is to set the date:

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

In the comments on this post, Stefan offers a nice one liner:

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

If you need speed, you can try to optimize as follows:

 d <= Date.today || d = d << 1200 
+3
source

When using %y in strptime code assumes that values ​​within 68 are counted in the 21st century, since descirbed here :

Year for a century (0-99). When a century is not specified otherwise (with a value for% C), values ​​in the range 69–99 refer to years in the twentieth century (1969–1999); values ​​in the range 00–68 refer to years in the twenty-first century (2000–2068).

In chronic jewels, by the way, the cutoff year is 64:

 Chronic.parse('15/10/64') # => 1964-10-15 12:00:00 +0200 Chronic.parse('15/10/63') # => 2063-10-15 12:00:00 +0300 
+3
source

Add Chronic Stone to Your Gemfile

gem 'chronic'

Then just parse it:

 Chronic.parse("15/10/68") => 1968-10-15 12:00:00 -0700 
-1
source

Source: https://habr.com/ru/post/978504/


All Articles