开发者

php rotator based on date and time

开发者 https://www.devze.com 2023-04-06 05:23 出处:网络
I found this script: <?php date_default_timezone_set(\'America/Los_Angeles\'); $time = date(\'H\');

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'; 
} 
?>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号