Ruby String to Date Conversion

Ruby on-RailsRubyDatetimeDate

Ruby on-Rails Problem Overview


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.

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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.

Solution 2 - Ruby on-Rails

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

Should be:

Date.strptime(updated, '%a, %d %b %Y %H:%M:%S %Z')

Solution 3 - Ruby on-Rails

str = "Tue, 10 Aug 2010 01:20:19 -0400 (EDT)"
str.to_date
=> Tue, 10 Aug 2010

Solution 4 - Ruby on-Rails

You can try https://rubygems.org/gems/dates_from_string:

Find date in structure:

text = "get car from repair 2015-02-02 23:00:10"
dates_from_string = DatesFromString.new
dates_from_string.find_date(text)

=> ["2015-02-02 23:00:10"]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondkrisView Question on Stackoverflow
Solution 1 - Ruby on-RailsklewView Answer on Stackoverflow
Solution 2 - Ruby on-RailssteenslagView Answer on Stackoverflow
Solution 3 - Ruby on-RailsWadesterView Answer on Stackoverflow
Solution 4 - Ruby on-RailsSergey ChechaevView Answer on Stackoverflow