PHP获取当前时间和上午/下午

时间:2016-02-24 17:31:01

标签: php html css

如何使用php获取当前时间和上午/下午?我所拥有的不起作用

这就是我目前所拥有的

$format1 = date("G");//this is supposed to get the current hour
$format2 = date("a");//this is supposed to get the current am or pm
$varies = "";//picture url that changes depending on time and am/pm
if(($format1 >=5 && $format1 <9) && ($format2 == "am")){
$varies = "url('Images/5to9am.PNG')";  //changes picture based on time and am/pm  
}
echo "body{ background-image: $varies"; //changes the background

2 个答案:

答案 0 :(得分:2)

您应熟悉此页面:

http://php.net/manual/en/function.date.php

在您的情况下,date('G')会返回 24小时格式。我不认为你想要的是什么。

尝试date('g') 12小时格式,如果您要在上午/下午查看它。

或者,保持24小时格式,并忽略上午/下午。

$hour = date("G"); // 24 hour format
if($hour >= 5 && $hour < 9) {
   // It's between 5am and 9am!!

答案 1 :(得分:0)

这里的日期函数给你几个小时b&#39;因为你传递H作为参数。$ time变量有所有时间。

根据服务器时间或网站时间,我会在一天的不同时间显示不同的背景图片。

  • 早上6点至10点 - sunrise.jpg
  • 上午10点至下午5点 - day.jpg
  • 5 pm-7pm- sunset.jpg
  • 晚上7点至晚上6点。

PHP代码:

<?php 

$time = date("H");    

if( $time >= 06 && $time < 10 )

    $img_name = 'sunrise.jpg';

if( $time >= 10 && $time < 17 )

    $img_name = 'day.jpg';

if( $time >= 17 && $time < 19 )

    $img_name = 'sunset.jpg';

if( $time >= 19 && $time < 6 )

    $img_name = 'night.jpg';

?>

<style>

    .my-class{background-image:url('http://yoursite.com/images/<?php echo $img_name;?>');}

</style>
相关问题