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?
strptime(updated,"%a, %d %m %Y %H:%M:%S %Z")
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.
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.
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')
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With