rubyist
rubyist

Reputation: 3132

how to convert string to date object in ruby

I am getting a date as a string like below:

"September 1998"

I tried like Date.parse("September 1998"), but it did not work.

How do I convert it into a ruby date object which returns string in above format?

Upvotes: 6

Views: 1374

Answers (3)

steenslag
steenslag

Reputation: 80065

Just prepend the missing "1 ":

str ="September 1998"
p Date.parse("1 " + str) # => #<Date: 1998-09-01 ((2451058j,0s,0n),+0s,2299161j)>

Upvotes: 2

Alex Pan
Alex Pan

Reputation: 4571

You could use the chronic gem:

require 'chronic'

t = Chronic.parse('September 1998', :guess => true) #returns a Time object
=> 1998-09-01 00:00:00 -0700

t.to_date #convert to Date object
=> <Date: 1998-09-16 ((2451073j,0s,0n),+0s,2299161j)>

Chronic was created by Tom Preston-Werner, who also co-created Github.

Upvotes: 4

Ryan Plant
Ryan Plant

Reputation: 1047

Date.strptime('September 1998', '%B %Y'). However, this will represent September 1st 1998, because date objects represent, well, dates.

Upvotes: 9

Related Questions