简体   繁体   中英

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.

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) { /* .. */ }
if ($currentTime > strtotime('16:00:00')) {
    // whatever you have to do here
}

使用date('H:i:s')以字符串格式获取时间并将其与“16:00:00”进行比较。

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

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

比较时间戳。

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

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

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)
?> 

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";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM