dkris dkris - 2 years ago 178
Ruby Question

Ruby String to Date Conversion

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:

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

  2. Chronic Parser

  3. Ruby: convert string to date

  4. Parsing date from text using Ruby

Please help me out with this.

Answer Source

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

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
puts Date.parse(Time.parse(str).utc.to_s)

I couldn't find simpler method to convert Time to Date.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download