I am faced with an issue in Ruby on Rails. I am looking to convert a string of format Tue, 10 Aug 2010 01:20:19 -0400 (EDT)
to a date object.
Is there anyway i could do this.
Here is what I've looked and tried at the following with no luck:
Date.strptime(updated,"%a, %d %m %Y %H:%M:%S %Z")
Please help me out with this.
Two steps: You need to convert your string into Date object. For that, use Date#strptime . You can use Date#strftime to convert the Date object into preferred 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.
What is wrong with Date.parse
method?
str = "Tue, 10 Aug 2010 01:20:19 -0400 (EDT)" date = Date.parse str => #<Date: 4910837/2,0,2299161> puts date 2010-08-10
It seems to work.
The only problem here is time zone. If you want date in UTC time zone, then it is better to use Time
object, suppose we have string:
str = "Tue, 10 Aug 2010 01:20:19 +0400" puts Date.parse str 2010-08-10 puts Date.parse(Time.parse(str).utc.to_s) 2010-08-09
I couldn't find simpler method to convert Time
to Date
.
Date.strptime(updated,"%a, %d %m %Y %H:%M:%S %Z")
Should be:
Date.strptime(updated, '%a, %d %b %Y %H:%M:%S %Z')
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