user1793514
user1793514

Reputation: 47

Odd Behavior from Date.strptime()

I'm doing a date conversion using strptime and it is normalizing my data to always have 2020 as the year and I'm not sure why. Specifically:

value = "2015/03/21"
value2 = Date.strptime(value, '%m/%d/%y')

produces a result where value2 = "2020-03-21" How do I get Date.strptime() to appropriately reflect the year?

Upvotes: 0

Views: 53

Answers (2)

spickermann
spickermann

Reputation: 106972

The second argument of strptime is the input format in which the date is provided not the expected output format. Therefore change it to:

value = "2015/03/21"
value2 = Date.strptime(value, '%Y/%m/%d')
#=> #<Date: 2015-03-21 ((2457103j,0s,0n),+0s,2299161j)>
             

Upvotes: 3

stolarz
stolarz

Reputation: 576

In value year is first, month is second. You want to create date object from string, so to correctly parse you should use correct order:

value = "2015/03/21"
value2 = Date.strptime(value, '%Y/%m/%d')
 => Sat, 21 Mar 2015 

Upvotes: 0

Related Questions