如何根据一天中的时间打印“早上/下午/晚上”?

时间:2016-11-20 20:59:12

标签: php

以下代码旨在向访客展示“早安,今天是------时间是-----”

但我一直得到“欢迎”而不是主要的问候。这是为什么?

<?php
$hour = date ("G");
$minute = date ("i");
$second = date ("s");
$msg = " Today is " . date ("l, M. d, Y.") . " And the time is " . date ("g:i a");

if ($hour = 00 && $hour <= 9 && $minute <= 59 && $second <= 59) 
{ $greet = "Good Morning,"; }

else {

if ($hour >= 10 && $hour <= 11 && $minute <= 59 && $second <= 59)
{ $greet = "Good Day,"; }

if ($hour >= 12 && $hour <= 15 && $minute <= 59 && $second <= 59)
{ $greet = "Good Afternoon,"; }

if ($hour >= 16 && $hour <= 23 && $minute <= 59 && $second <= 59)
{ $greet = "Good Evening,"; }

else { $greet = "Welcome,"; }
 }
echo $greet.$msg;
?>

有关如何完成此操作的任何想法?

如何使用php自动获取访问者的时区。我服务器的默认时区是拉各斯/非洲。我希望上面的代码向访问者显示他们当地的时间和日期。

2 个答案:

答案 0 :(得分:1)

你的问题在这里

 if ($hour = 00 && $hour <= 9 && $minute <= 59 && $second <= 59) 

这样你就可以将00分配给$小时而所有其他条件都失败

你需要

if ($hour == 0 && $hour <= 9 && $minute <= 59 && $second <= 59) 

解决了问题还有其他问题

你应该记住php date()函数返回一个字符串 解决你的代码问题有几种方法,这些只是一些建议 所以你应该使用适当的演员来构造字符串(而不是数字)或者将字符串转换成数字用于表示

期待您是否也可以避免分钟检查(总是&lt; = 59)这意味着您的代码可以

  <?php 

      $hour = date("G"); 
      $minute = date("i"); 
      $second = date("s"); 
      $msg = " Today is " . date("l, M. d, Y.") . " And the time is " . date("g:i a"); 

      if ( (int)$hour == 0 && (int)$hour <= 9 ) { 
          $greet = "Good Morning,"; 
      } else if ( (int)$hour >= 10 && (int)$hour <= 11 ) { 
          $greet = "Good Day,"; 
      } else if ( (int)$hour >= 12 && (int)$hour <= 15 ) { 
          $greet = "Good Afternoon,"; 
      } else if ( (int)$hour >= 16 && (int)$hour <= 23 ) { 
          $greet = "Good Evening,"; 
      } else { 
          $greet = "Welcome,"; 
      }

      echo $greet.$msg;
  ?>

答案 1 :(得分:0)

试试这个......

<?php
    $hour = date ("G");
    $minute = date ("i");
    $second = date ("s");
    $msg = " Today is " . date ("l, M. d, Y.") . " And the time is " . date ("g:i a");

    if ($hour == 00 && $hour <= 9 && $minute <= 59 && $second <= 59){
        $greet = "Good Morning,";
        }else if ($hour >= 10 && $hour <= 11 && $minute <= 59 && $second <= 59){
            $greet = "Good Day,";
            }else if ($hour >= 12 && $hour <= 15 && $minute <= 59 && $second <= 59){
                $greet = "Good Afternoon,";
            }else if ($hour >= 16 && $hour <= 23 && $minute <= 59 && $second <= 59){
                $greet = "Good Evening,";
            }else {
                $greet = "Welcome,";
            }

        }

    echo $greet.$msg;
?>

我建议你阅读一些内容