Cover by Leonard Richardson, Lucas Carlson

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

3.2. Parsing Dates, Precisely or Fuzzily

Problem

You want to transform a string describing a date or date/time into a Date object. You might not know the format of the string ahead of time.

Solution

The best solution is to pass the date string into Date.parse or DateTime.parse. These methods use heuristics to guess at the format of the string, and they do a pretty good job:

	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"

Discussion

The 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 example how Date.parse assumed that 2/9/2007 was an American (month first) date instead of a European (day first) date. parse also tends to misinterpret two-digit years:

	Date.parse('2/9/07').to_s                   # => "0007-02-09"

Let's say that Date.parse 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 DateTime.strptime or Date.strptime. If the date string matches up with the format string, you'll get a Date or DateTime object back. You may already be familiar with this technique, ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required