PHP if / else语句带有格式化日期以确定当天的部分

I am trying to make a simple if/else statement in PHP. Someting simple like this:

<?php 
$time = 13;
if ($time < 12) {
  echo "Morning";
} else {
  echo "Afternoon or evening";
}
?>

The problem is the value i receive from the database is an unformatted time format (like: 2014-09-08 06:00:00). I can format this date using:

$time->format('H');

To strip the date from the day, month and year. But you can not use this as a variable. This is what i am trying to do:

<?php $deliverytime = new DateTime('2014-09-08 06:00:00');
$deliverytime->format('H');
if ($deliverytime < 12) {
  echo "Morning";
} else {
  echo "Afternoon or evening";
}
?>

I now this is not working because i am trying to use a formatted date as a variable which does not work. Is there another way to determine the part off the day using a formatted date?

Regards, Matthijs

<?php 
     $deliverytime = new DateTime('2014-09-08 06:00:00');
     $hour = $deliverytime->format('H');
     if ($hour < 12) {
       echo "Morning";
     } else {
       echo "Afternoon or evening";
     }
?>

$deliverytime->format() is a method that returns the formatted date and you have to store it somewhere to use what that method returns, as the code above shows.

As it is, you're passing the entire object to the if statement, you need just the result of the method you're using.

But you can not use this as a variable

Yes you can. This works fine:

<?php 
    $deliverytime = new DateTime('2014-09-08 06:00:00');
    $hour = (int) $deliverytime->format('H');

    if ($hour < 12) {
        echo "Morning";
    } else {
        echo "Afternoon or evening";
    }
?>

I wouldn't use DateTime for something so easy. This is what I would do:

$date = "2014-09-08 06:00:00";
$date = strtotime($date);
if (date('H', $date) < 12){
  echo "Morning";
} else {
  echo "Afternoon or evening";
}

Maybe not the best way, but you can also get the value using preg match:

preg_match('/[0-9]{4}\-[0-9]{2}-[0-9]{2} 0?([0-9]+)\:[0-9]{2}\:[0-9]{2}/', $date, $match);
$hour = intval($match[1]);