I need a method like this:
function check_date_format($date, $allowOverflow = false, $allowRelativeFormats = false)
which was return bool if string is correct date/time according to the boolean flags.
Where $allowOverflow = false means dates that are overflow like 2020-13-13 (2021-01-13) are not correct,
and $allowRelativeFormats = false means that relative dates like 'today', 'tomorow' 'x day ago' etc. are incorrect
There is any possibility to write that functions using Carbon / DateTime class without defining own arrays like $availableFormats inside this function?
Examples to understood my expected result:
check_date_format('asdgasd'); // false
check_date_format('2020-02-01'); // true
check_date_format('2020-02-30'); // false
check_date_format('2020-02-30', true); // true
check_date_format('10:00'); // true
check_date_format('tomorrow'); // false
check_date_format('tomorrow', false, true); // true
check_date_format('now'); // false
I tried to use date_parse() in such way:
function check_date_format($date, $allowOverflow = false, $allowRelativeFormats = false)
{
$dateInfo = date_parse($date);
$isCorrectDate = $dateInfo['error_count'] === 0;
if ($isCorrectDate) {
$isRelative = array_key_exists('relative', $dateInfo);
$isOverflowed = $dateInfo['warning_count'] > 0;
if (!$allowOverflow && $isOverflowed) {
return false;
}
if (!$allowRelativeFormats && ($isRelative || strtolower(trim($date)) === 'now')) {
return false;
}
return true;
}
return false;
}
but this solution assumes that 'warnings' means overflows which I'm not sure.