2

I am trying to parse a string 26/03/2012, in dd/mm/yyyy format to Ruby's Date using Date.strptime, as follows:

#!/usr/bin/ruby
require 'date'
puts 'Ruby Version: ' + RUBY_VERSION
date_str = '26/03/2012'

date = Date.strptime(date_str, "%d/%m/%y")
puts 'Parsed Date: ' + date.to_s

The output is:

Ruby Version: 1.8.7
Parsed Date: 2020-03-26

The year part has become 2020, instead of 2012!

2 Answers 2

4

That should be %Y upper case, rather than %y:

date = Date.strptime(date_str, "%d/%m/%Y")
puts 'Parsed Date: ' + date.to_s
# Parsed Date: 2012-03-26

From the docs:

 Date (Year, Month, Day):
    %Y - Year with century (can be negative, 4 digits at least)
            -0001, 0000, 1995, 2009, 14292, etc.
    %C - year / 100 (round down.  20 in 2009)
    %y - year % 100 (00..99)

Since %y expects two digits only, it takes the first two 20 and assumes that to be a 2 digit representation of 2020, since 2020 % 100 = 20.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks! The documentation %y - year % 100 indicates that all 4 digits of the year part should be read, if it reads first 2 digits only then there is no point of doing year % 100, which would same as year when year < 100! But as you say it perhaps reads only first 2 digits!
Yeah I saw (00..99) in the docs, this part is contradicting the %y - year % 100 part! Is not it? :)
I think its doing %y - year / 100, tried with 4042 as the year and it printed 2040 as the year. Had it been doing %y - year % 100 I would got what I wanted.
@Curious Not contradictory, just confusing. You are expected to be supplying the result of year % 100, so if you give it 20 as the result of year % 100, it extrapolates the current century. The %y - part isnt't subtraction, it's just how they printed it in the docs. No calculation takes place.
The result of 2040 from 4042 is exactly expected because again, 2040 % 100 = 40. It expects 2 digits and uses the first 2 it finds. The others are discarded because it doesn't realize you are trying to give it the year 4042, it just sees a string "4042"
1

If you change your strptime function to date = Date.striptime(date_str, "%d/%m/%Y")

it will output correctly.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.