Se si desidera accettare date utilizzando l'ordinamento americano (mese, data, anno) per i formati di stile europeo (utilizzando trattino o periodo come giorno, mese, anno) pur accettando altri formati , è possibile estendere la classe DateTime:
/**
* Quietly convert European format to American format
*
* Accepts m-d-Y, m-d-y, m.d.Y, m.d.y, Y-m-d, Y.m.d
* as well as all other built-in formats
*
*/
class CustomDateTime extends DateTime
{
public function __construct(string $time="now", DateTimeZone $timezone = null)
{
// convert m-d-y or m.d.y to m/d/y to avoid PHP parsing as d-m-Y (substr avoids microtime error)
$time = str_replace(['-','.'], '/', substr($time, 0, 10)) . substr($time, 10 );
parent::__construct($time, $timezone);
}
}
// usage:
$date = new CustomDateTime('7-24-2019');
print $date->format('Y-m-d');
// => '2019-07-24'
In alternativa, è possibile creare una funzione per accettare mdY e generare Ymd:
/**
* Accept dates in various m, d, y formats and return as Y-m-d
*
* Changes PHP's default behaviour for dates with dashes or dots.
* Accepts:
* m-d-y, m-d-Y, Y-m-d,
* m.d.y, m.d.Y, Y.m.d,
* m/d/y, m/d/Y, Y/m/d,
* ... and all other formats natively supported
*
* Unsupported formats or invalid dates will generate an Exception
*
* @see https://www.php.net/manual/en/datetime.formats.date.php PHP formats supported
* @param string $d various representations of date
* @return string Y-m-d or '----' for null or blank
*/
function asYmd($d) {
if(is_null($d) || $d=='') { return '----'; }
// convert m-d-y or m.d.y to m/d/y to avoid PHP parsing as d-m-Y
$d = str_replace(['-','.'], '/', $d);
return (new DateTime($d))->format('Y-m-d');
}
// usage:
<?= asYmd('7-24-2019') ?>
// or
<?php echo asYmd('7-24-2019'); ?>