Read more

Rails: use Date.strptime to parse date

Daniel Straßner
October 22, 2018Software engineer at makandra GmbH

It is very common to parse dates from strings. It seems obvious to use Date.parse for this job. However this method does not validate the input and tries to guess the format of the string.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

This can lead to a very unexpected results:

> Date.parse('Foobar_09_2018')
Tue, 09 Oct 2018

In most of the cases it would be better to use Date.strptime as you can provide a date or time pattern to match against.

> Date.strptime('Foobar_09_2018', '%d_%m_%Y')
ArgumentError (invalid strptime format - `%d_%m_%Y')
> Date.strptime('01_09_2018', '%d_%m_%Y')
Sat, 01 Sep 2018

other use cases:

ambiguous date strings

>> Date.parse('01.02.03')
=> Sat, 03 Feb 2001

In Germany you would expect this to be parsed as 01 Feb 2003.
Be more explicit and provide a date pattern:

>> Date.strptime('01.02.03', '%d.%m.%y')
=> Sat, 01 Feb 2003
Posted by Daniel Straßner to makandra dev (2018-10-22 15:18)