A repository of tips and tricks (in both English and French) curated by Mirego’s engineering team.
  • ruby

Parsing french dates with Ruby

Ruby is able to parse dates when they are provided as strings:

DateTime.parse("March 18, 2019").to_s
# => "2019-03-18T00:00:00+00:00"

DateTime.parse("April 2, 2019").to_s
# => "2019-04-02T00:00:00+00:00"

We had similar code using DateTime#parse, with a small difference: date strings were in french.

DateTime.parse("18 mars 2019").to_s
# => "2019-03-18T00:00:00+00:00"

DateTime.parse("2 avril 2019").to_s
# => ArgumentError: invalid date

It looks like Ruby is only able to parse the first one because "mars" first three letters are MAR, which are the same first three letters as "march".

The lesson here: do not trust Ruby to parse french dates with DateTime#parse — use a real i18n-compatible parser like Chronic.