我有一个方法可以返回当前日期时间,或者根据给定日期返回另一个日期时间。
我想将另一个日期设置为与现在相同的时间。
这是我的代码:
/**
* @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');
它有效,但是我不得不使用$currentDate
来提取它的小时,分钟和秒。
还有另一种更简洁的方法吗?
答案 0 :(得分:2)
使用DateTime::createFromFormat
时,格式为的所有信息都将设置为当前时间。它还为您节省了手动格式验证。所以:
function getFormattedDate($date) {
$ts = DateTime::createFromFormat('Y-m-d', $date) ?: new DateTime;
return $ts->format('Y-m-d H:i:s');
}
答案 1 :(得分:-1)
您可以尝试使用strtotime。它允许您简单地添加您想要的时间量,例如:
strtotime("+1 day")
它会接受许多不同的输入,例如:+1天,+ 3天,+ 1周,+ 1个月,+ 1周5天等。