简体   繁体   English

PHP If / else语句(带有格式化日期)来确定一天中的哪一天

[英]PHP If/else statement with formatted date to determine the part of the day

I am trying to make a simple if/else statement in PHP. 我试图在PHP中做一个简单的if / else语句。 Someting simple like this: 像这样简单:

<?php 
$time = 13;
if ($time < 12) {
  echo "Morning";
} else {
  echo "Afternoon or evening";
}
?>

The problem is the value i receive from the database is an unformatted time format (like: 2014-09-08 06:00:00). 问题是我从数据库接收的值是未格式化的时间格式(例如:2014-09-08 06:00:00)。 I can format this date using: 我可以使用以下格式设置日期:

$time->format('H');

To strip the date from the day, month and year. 从日期,月份和年份中删除日期。 But you can not use this as a variable. 但是您不能将其用作变量。 This is what i am trying to do: 这就是我想要做的:

<?php $deliverytime = new DateTime('2014-09-08 06:00:00');
$deliverytime->format('H');
if ($deliverytime < 12) {
  echo "Morning";
} else {
  echo "Afternoon or evening";
}
?>

I now this is not working because i am trying to use a formatted date as a variable which does not work. 我现在这不起作用,因为我试图将格式化日期用作不起作用的变量。 Is there another way to determine the part off the day using a formatted date? 还有另一种方法可以使用格式化日期来确定当天的零件?

Regards, Matthijs 问候,Matthijs

<?php 
     $deliverytime = new DateTime('2014-09-08 06:00:00');
     $hour = $deliverytime->format('H');
     if ($hour < 12) {
       echo "Morning";
     } else {
       echo "Afternoon or evening";
     }
?>

$deliverytime->format() is a method that returns the formatted date and you have to store it somewhere to use what that method returns, as the code above shows. $deliverytime->format()是一种返回格式化日期的方法,您必须将其存储在某个地方才能使用该方法返回的内容,如上面的代码所示。

As it is, you're passing the entire object to the if statement, you need just the result of the method you're using. 实际上,您要将整个对象传递给if语句,您只需要使用的方法的结果即可。

But you can not use this as a variable 但是您不能将其用作变量

Yes you can. 是的你可以。 This works fine: 这很好用:

<?php 
    $deliverytime = new DateTime('2014-09-08 06:00:00');
    $hour = (int) $deliverytime->format('H');

    if ($hour < 12) {
        echo "Morning";
    } else {
        echo "Afternoon or evening";
    }
?>

I wouldn't use DateTime for something so easy. 我不会使用DateTime这么简单。 This is what I would do: 这就是我要做的:

$date = "2014-09-08 06:00:00";
$date = strtotime($date);
if (date('H', $date) < 12){
  echo "Morning";
} else {
  echo "Afternoon or evening";
}

Maybe not the best way, but you can also get the value using preg match: 也许不是最好的方法,但是您也可以使用preg match获得值:

preg_match('/[0-9]{4}\-[0-9]{2}-[0-9]{2} 0?([0-9]+)\:[0-9]{2}\:[0-9]{2}/', $date, $match);
$hour = intval($match[1]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM