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


PHP Get Current Time and AM/PM

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

这是我目前拥有的

$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

您应该熟悉此页面:

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!!

这里的日期函数给你几个小时 b'coz 你传递H作为参数。$time变量都有所有时间。

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

  • 早上 6 点至上午 10 点 - 日出.jpg
  • 上午 10 点至下午 5 点 - 白天.jpg
  • 下午 5 点至晚上 7 点 - 日落.jpg
  • 晚上 7 点至早上 6 点.jpg

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>