<?php
function getFormattedDate(string $date, string $format = 'm/d/Y', string $yearPadding = '19'): string {
$sanitizedDate = preg_replace_callback(
'~^(\d+)(\D)(\d+)\2(\d{2}|\d{4})$~',
fn($m) => sprintf('%02d/%02d/%d', $m[1], $m[3], str_pad($m[4], 4, $yearPadding, STR_PAD_LEFT)),
$date
); // sanitize
$d = DateTime::createFromFormat($format, $sanitizedDate); // attempt to parse
if (!$d) {
throw new Exception("Could not parse date: $date");
}
$formattedDate = $d->format($format);
if ($formattedDate !== $sanitizedDate) {
throw new Exception("Date not in a desired American format: $date");
} else {
return $date;
}
}
$tests = [
'1-1-1992',
'1-1-92',
'1-01-1992',
'1-01-92',
'01-1-1992',
'01-1-92',
'01-01-1992',
'01-01/92',
'1/1/1992',
'1/1/92',
'1/01/1992',
'1/01/92',
'01/1/199',
'01/1/92',
'01/01/1992',
'01/01/92'
];
foreach ($tests as $test) {
try {
echo getFormattedDate($test);
} catch (Exception $e) {
echo $e->getMessage();
}
echo "\n";
}
preferences:
31.74 ms | 405 KiB | 6 Q