Fishtoaster
Fishtoaster

Reputation: 1819

Ruby date parsing

I'm sure I'm missing something obvious, but - I'm trying to parse a date like "8/5/2018" (in m/d/y format). Ruby seems perfectly capable of creating dates in this format using the format string %-m/%-d/%Y and strftime, but for some reason strptime can't read it?

[1] pry(main)> require 'date'
=> true
[2] pry(main)> format = '%-m/%-d/%Y'
=> "%-m/%-d/%Y"
[3] pry(main)> today = Date.today.strftime(format)
=> "8/5/2018"
[4] pry(main)> Date.strptime(today, format)
ArgumentError: invalid date
from (pry):4:in `strptime'

Does strptime use a different set of format keys than strftime (the ruby docs seem to suggest that they're the same)? Or am I missing something else here?

Upvotes: 1

Views: 646

Answers (2)

mehrnoush
mehrnoush

Reputation: 21

the problem is about format! if you change it to

%m/%d/%Y

, it will be fix !

format = '%m/%d/%Y'
today = Date.today.strftime(format)
Date.strptime(today, format)
#=> Mon, 06 Aug 2018

Upvotes: 0

Simple Lime
Simple Lime

Reputation: 11035

They use the same format keys, but the docs for strptime state:

strptime does not support specification of flags and width unlike strftime.

So the issue is those flags (in this case the hyphens (-). Kind of dumb that you can't just use the same format specifier for inputting dates, as well as outputting them, but it is what it is, you could do:

Date.strptime(today, format.delete('-'))

Upvotes: 3

Related Questions