简体   繁体   中英

php rotator based on date and time

I found this script:

<?php
date_default_timezone_set('America/Los_Angeles'); 
$time = date('H'); 
if($time < 12){ 
   echo 'good morning'; 
}else if($time >= 20 and $time < 21){ 
    echo 'good afternoon'; 
}else{ 
    echo 'good evening'; 
} 
?>

and would like to extend it to set it to specific dates and times, like:

  • if time < 2011-11-30 13:59 echo 'before'
  • else if time >= 2011-11-30 14:00 and < 2012-12-15 20:00 echo 'now'
  • else echo 'after'

being a php noob, I looked all over the web, but the only examples I could find are either week days or hours but not the combination above. Could someone be so kind and help me get this set up? Thank you in advance

Use php's mktime function to create a unix epoch time from any date you want.

mktime(12, 34, 56, 7, 8, 2009);  // 12:34:56 on 7-8-2009 

This can be then compared against time which returns the current unix epoch.

$now = time();
$desired = mktime(12, 34, 56, 7, 8, 2009);
if ($now < $desired)
    echo "Not yet!";
else
    echo "It is past time!";
date_default_timezone_set('America/Los_Angeles'); 
$time = new DateTime(); 
if($time < new DateTime('2011-11-30 13:59')){ 
   echo 'before'; 
}else if($time >= new DateTime('2011-10-31 14:00') and $time < new DateTime('2012-12-15 20:00')){ 
    echo 'now'; 
}else{ 
    echo 'after'; 
} 

Just change the input of the date() function, and the if conditions:

<?php
date_default_timezone_set('America/Los_Angeles'); 
$time = strtotime(date('Y-m-d H:m')); 
if($time < strtotime('2011-11-30 13:59')){ 
   echo 'Before'; 
}else if($time >= strtotime('2011-11-30 14:00') and $time < strtotime('2011-11-30 20:00')){ 
   echo 'Now'; 
}else{ 
   echo 'After'; 
} 
?>

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