Search code examples
phpdateif-statementformatted

PHP If/else statement with formatted date to determine the part of the day


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


Solution

  • <?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.