@ 2022-02-17T23:39:30Z <?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";
}
Enable javascript to submit You have javascript disabled. You will not be able to edit any code.
Output for 7.4.0 - 7.4.33 , 8.0.1 - 8.0.30 , 8.1.0 - 8.1.27 , 8.2.0 - 8.2.18 , 8.3.0 - 8.3.6 1-1-1992
1-1-92
1-01-1992
1-01-92
01-1-1992
01-1-92
01-01-1992
Could not parse date: 01-01/92
1/1/1992
1/1/92
1/01/1992
1/01/92
Date not in a desired American format: 01/1/199
01/1/92
01/01/1992
01/01/92
preferences:dark mode live preview
143.34 ms | 402 KiB | 120 Q