新的DateTime,但是当前小时

时间:2017-06-23 15:32:54

标签: php datetime

我有一个方法可以返回当前日期时间,或者根据给定日期返回另一个日期时间。

我想将另一个日期设置为与现在相同的时间。

这是我的代码:

/**
 * @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来提取它的小时,分​​钟和秒。

还有另一种更简洁的方法吗?

2 个答案:

答案 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天等。

PHP文档:http://php.net/manual/en/function.strtotime.php