How to convert string to object date in ruby

I get the date as a string, as shown below:

"September 1998" 

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

How to convert it to a ruby ​​date object that returns a string in the above format?

+6
source share
3 answers

Date.strptime('September 1998', '%B %Y') . However, it will be September 1, 1998, since the dates of the objects represent, well, dates.

+9
source

You can use a chronic stone :

 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.

+4
source

Just add the missing "1":

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

Source: https://habr.com/ru/post/987380/


All Articles