QR Code contains TinyURL of this article.The dateFinder PHP Class

There are three good date-handling functions provided by PHP: checkdate, date_parse and strtotime. Checkdate will validate any Gregorian date, date_parse returns detailed information on a valid date and strtotime will parse almost any textual representation of a date. As clever as they are though, these functions can’t help with certain date strings.

Consider the following:

  • 1st January 1900: Seems simple enough, but the date functions don’t react well to dates earlier than 1st January 1970;
  • December '61: We often abbreviate years with a leading apostrophe, but the date functions of PHP don’t like this either;
  • 16th: dateFinder assumes that the user means the 16th of the current month;
  • 1941: A valid year, but earlier than 1970. Could cause problems;
  • This august body met on the 15th April, 1982: The date here is obvious to a human reader, but a text-to-date parser will stumble over the use of the word “august” in this context.

I thought it would be interesting to write a date parser that can handle these edge-cases and the result is the dateFinder PHP class.

Given a string, dateFinder will try to extract a valid date from it. It returns an array containing a year, month and day corresponding with the first date it finds. The array will optionally contain a “range” key, if dateFinder was unable to determine an exact date from the input string (ie: it could only extract a year, month or both).

If dateFinder is unable to extract a valid date, then it will simply return a boolean false.

For example:

  • 1969: returns (1969, 1, 1, true)
  • Dec '69: returns (1969, 12, 1, true)
  • 7th December, 1969: returns (1969, 12, 7)
  • 64th December, 1969: returns false

Usage

<?php
$df = new dateFinder('December 7th, 1969');
var_dump($df->parsedDate);

Code

This project is on GitHub.