Posted 4 months ago. Visible to the public. Repeats.

Rails: use Date.strptime to parse date

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.

This can lead to a very unexpected results:

Copy
> 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.

Copy
> 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

Copy
>> 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:

Copy
>> Date.strptime('01.02.03', '%d.%m.%y') => Sat, 01 Feb 2003

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Owner of this card:

Avatar
Daniel Straßner
Last edit:
4 months ago
by Arne Hartherz
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Daniel Straßner to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more