php greater than certain time

I am trying to make a simple function to output 2 different lines of text depending on the time of the day. I want it to say after 4pm – Next day delivery will be processed the following day.

I have wrote this so far:

<?php

   $currentTime = time() + 3600;
   echo date('H:i',$currentTime);                 

?>   

However as the date function returns a string, I am unsure of how to use an IF statement to check whether the time is greater than 16:00.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Should do it

if (((int) date('H', $currentTime)) >= 16) {
  // .. do something
}

Because PHP is weak-typed you can omit the (int)-casting.

As a sidenote: If you name a variable $currentTime, you shouldn’t add 1 hour to it, because then its not the current time anymore, but a time one hour in the future 😉 At all

if (date('H') >= 16) { /* .. */ }

Solution 2

if ($currentTime > strtotime('16:00:00')) {
    // whatever you have to do here
}

Solution 3

Use date('H:i:s') to get the time in a string format and compare it with “16:00:00”.

Solution 4

Compare the timestamps.

if (strtotime($date) < strtotime('16:00'))

Solution 5

if(mktime(16, 0, 0) < time()) {
    echo "Next day delivery will be processed the following day.";
} else {
   echo "Will be processed today.";
}

Solution 6

Maybe a small improvement, if you want some more accuracy:

if ( (int) date('Hi', $currentTime)  > 1600 ) {
    // .. do something
}

Solution 7

you can also check the difference between two Dates:-

<?php
$date1 = new DateTime("now");
$date2 = new DateTime("tomorrow");

var_dump($date1 == $date2);    //bool(false)
var_dump($date1 < $date2);    //bool(true)
var_dump($date1 > $date2);    //bool(false)
?> 

Solution 8

Try this

    function checkTime($time1,$time2)
{
  $start = strtotime($time1);
  $end = strtotime($time2);
  if ($start-$end > 0)
    return 1;
  else
   return 0;
}

$currentTime = time() + 3600;
$time1 = date('H:i',$currentTime);
$time2 = '16:00';

if(checkTime($time1,$time2))
   echo "First parameter is greater";
else
   echo "Second parameter is greater";

Solution 9

I used this for updating something 3 times throughout the day…

$my_time= strtotime('now')-18000;//Now. My servers timezone is 5hrs ahead.
$my_day= strtotime('today')-86400; //today midnight central time.
$my_eve= $my_day +54000; //3pm central

if ($my_time > $my_day + 32400 && $my_time < $my_eve){

echo date('F j, Y, g:i a', $my_day + 32400); //9am

}elseif ($my_time > $my_eve){

echo date('F j, Y, g:i a', $my_eve); //3pm

}else{  

echo date('F j, Y, g:i a', $my_day);} //midnight

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply