I've got a method which can return me the current datetime, or another one depending on a given date.
I want to set the other date to the same time as now.
Here's my code :
/**
* @param string $date
* @return string
*/
function getDateFormatted($date = '')
{
if (preg_match('#^[0-9]{4}-[0-9]{2}-[0-9]{2}$#', $date)) {
$currentDate = new DateTime();
$date = new DateTime($date);
$date->setTime(
$currentDate->format('H'),
$currentDate->format('i'),
$currentDate->format('s')
);
} else {
$date = new DateTime();
}
return $date->format('Y-m-d H:i:s');
}
$date = getDateFormatted();
$otherDate = getDateFormatted('2017-09-01');
It works, but it bugs me to have to use the $currentDate
to extract its hours, minutes and seconds.
Is there another, neater way to do it ?