1.20.x date.inc date_make_iso_valid($iso_string)

Replace specific ISO values using patterns.

Function will replace ISO values that have the pattern 9999-00-00T00:00:00 with a pattern like 9999-01-01T00:00:00, to match the behavior of non-ISO dates and ensure that date objects created from this value contain a valid month and day. Without this fix, the ISO date '2020-00-00T00:00:00' would be created as November 30, 2019 (the previous day in the previous month).

@TODO Expand on this to work with all sorts of partial ISO dates.

Parameters

string $iso_string: An ISO string that needs to be made into a complete, valid date.

Return value

mixed|string: replaced value, or incoming value.

File

includes/date.inc, line 1666
Date API functions and constants.

Code

function date_make_iso_valid($iso_string) {
  // If this isn't a value that uses an ISO pattern, there is nothing to do.
  if (is_numeric($iso_string) || !preg_match(DATE_REGEX_ISO, $iso_string)) {
    return $iso_string;
  }
  // First see if month and day parts are '-00-00'.
  if (substr($iso_string, 4, 6) == '-00-00') {
    return preg_replace('/([\d]{4}-)(00-00)(T[\d]{2}:[\d]{2}:[\d]{2})/', '${1}01-01${3}', $iso_string);
  }
  // Then see if the day part is '-00'.
  elseif (substr($iso_string, 7, 3) == '-00') {
    return preg_replace('/([\d]{4}-[\d]{2}-)(00)(T[\d]{2}:[\d]{2}:[\d]{2})/', '${1}01${3}', $iso_string);
  }

  // Fall through, no changes required.
  return $iso_string;
}