You want to transform a string describing a date or date/time
Date object. You might not
know the format of the string ahead of time.
The best solution is to pass the date string into
DateTime.parse. These methods use heuristics
to guess at the format of the string, and they do a pretty good
require 'date' Date. parse('2/9/2007').to_s # => "2007-02-09" DateTime.parse('02-09-2007 12:30:44 AM').to_s # => "2007-09-02T00:30:44Z" DateTime. parse('02-09-2007 12:30:44 PM EST').to_s # => "2007-09-02T12:30:44-0500" Date.parse('Wednesday, January 10, 2001').to_s # => "2001-01-10"
parse methods can save
you a lot of the drudgework associated with parsing times in other programming languages, but they
don't always give you the results you want. Notice in the first
Date.parse assumed that
2/9/2007 was an American (month first) date instead of a European (day
parse also tends to
misinterpret two-digit years:
Date.parse('2/9/07').to_s # => "0007-02-09"
Let's say that
doesn't work for you, but you know that all the dates you're processing will be formatted a certain
way. You can create a format string using the standard
strftime directives, and pass it along with
a date string into
Date.strptime. If the date string matches up
with the format string, you'll get a
DateTime object back. You may already be familiar with this technique, ...