6
$\begingroup$

I know you can use DateObject[{"05-08-2022", {"Day", "Month", "Year" }}] to tell WL the date format explicitly, but a rigid format is often inadequate for interpreting dates from messy sources (such as TextCases) where you don't know exactly in advance what you're going to find. You could end up with dates like:

dates = {
  "05-08-2022", "2 June 1999", "March 5th 2001", 
  "2022-04-03", "2021-02-11T15:30"
}

Using DateObject[{date, format}] will not work here, but just vanilla DateObject /@ dates almost does the right thing. Unfortunately, though, you can't just tell DateObject to interpret "05-08-2022" as mm-dd-yyyy in case of ambiguity. Instead, it uses your locale to infer your preferred date format and uses that, which is not what you may always want.

How do you extend this auto-magic functionality of DateObject (or Interpreter["Date"]) so you can tell it you want day-first or month-first interpretations for edge cases?

$\endgroup$

1 Answer 1

9
$\begingroup$

To handle this problem, I wrote a new ResourceFunction called DateAmbiguityBreak. It piggybacks off Interpreter["Date" | "DateTime", AmbiguityFunction -> All] and allows you to easily disambiguate between mm-dd-yyyy and dd-mm-yyyy:

dates = {
  "05-08-2022", "2 June 1999", "March 5th 2001", 
  "2022-04-03", "2021-02-11T15:30"
};
ResourceFunction["DateAmbiguityBreak"]["DayFirst"] @ dates
ResourceFunction["DateAmbiguityBreak"]["MonthFirst"] @ dates

{DateObject[{2022, 8, 5}, "Day"], DateObject[{1999, 6, 2}, "Day"], DateObject[{2001, 3, 5}, "Day"], DateObject[{2022, 4, 3}, "Day"], DateObject[{2021, 2, 11, 15, 30}, "Minute", "Gregorian", 1.]}

{DateObject[{2022, 5, 8}, "Day"], DateObject[{1999, 6, 2}, "Day"], DateObject[{2001, 3, 5}, "Day"], DateObject[{2022, 4, 3}, "Day"], DateObject[{2021, 2, 11, 15, 30}, "Minute", "Gregorian", 1.]}

There are some subtleties about the implementation of this function that I wrote up in the documentation.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.