Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string to date with Ruby

I have date as string in such format: 23 Nov. 2014. Sure, it's easy to convert this string into date with such expression:

Date.strptime(my_string, '%d %b. %Y')

But there is one issue when month is May - there is no dot, like 23 May 2014. And my expression breaks.

Could somebody help with this issue? How can I make universal expression for my cases?

like image 479
ktaras Avatar asked Nov 22 '14 22:11

ktaras


People also ask

How to convert a string to date in ruby?

strptime(updated,"%a, %d %m %Y %H:%M:%S %Z")

How do I change the date format in Ruby?

Ruby provides two classes to format date string strftime and strptime . Method parse of class Date converts string into date object with given directives. E.g. The provided directives can be changed according to given string format.

How do you parse a date in Ruby?

Ruby | DateTime parse() function DateTime#parse() : parse() is a DateTime class method which parses the given representation of date and time, and creates a DateTime object. Return: given representation of date and time, and creates a DateTime object.


2 Answers

Remove the period from my_string and from the date pattern.

Date.strptime(my_string.sub('.', ''), '%d %b %Y')

That's assuming you have at most one dot in my_string. If there may be several, use gsub.

Date.strptime(my_string.gsub('.', ''), '%d %b %Y')
like image 81
Michael Laszlo Avatar answered Sep 30 '22 10:09

Michael Laszlo


I think you're using the wrong method. Date#parse should work with almost "anything" (see TinMan answer and comment for clarification of when not to use parse) and provide the same object:

p Date.parse('23 Nov 2014') #=> #<Date: 2014-11-23 ((2456985j,0s,0n),+0s,2299161j)>
p Date.parse('23 Nov. 2014') #=> #<Date: 2014-11-23 ((2456985j,0s,0n),+0s,2299161j)> same object as with the previous line
like image 36
daremkd Avatar answered Sep 30 '22 09:09

daremkd