6

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?

3
  • 2
    But "September 1998" is not a date, it is missing the day. Commented May 17, 2015 at 18:48
  • yes. But I am getting like this only. So is there any way I can convert it to 09-1998 Commented May 17, 2015 at 18:50
  • Aways specify a format when parsing dates, most especially if you're using formats that might include day and month. Enforce the format based on the user's locale and be sure dates are disambiguated just in case. Commented May 17, 2015 at 22:33

3 Answers 3

9

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

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

Comments

4

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.

Comments

2

Just prepend the missing "1 ":

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

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.