【问题标题】:If statement returning false result using date and strtotime如果语句使用日期和 strtotime 返回错误结果
【发布时间】:2023-03-14 20:19:02
【问题描述】:

我正在尝试使用 if 语句来表示“如果今天介于两个日期之间,请执行此操作...”等。

它不起作用,我完全不知所措,因为据我所知 - 它应该起作用!

if (date('d/m/y', strtotime('now')) >= date('d/m/y', strtotime('1 January 2021')) && date('d/m/y', strtotime('now')) <= date('d/m/y', strtotime('31 January 2021'))):
    echo 'true';
else:
    echo 'false';
endif;

今天是 2020 年 12 月 3 日 - 为什么它告诉我这个说法是真的?

PS。如果我将其更改为 &gt; 30th December 2020&lt; 1st February 2021 中的任何一个或两者都可以,但我很小心这样做,以防它只是一个小故障并且我犯了一个明显的编码错误。

【问题讨论】:

    标签: php date strtotime


    【解决方案1】:

    首先。现在不是 12 月 3 日,而是 12 月 1 日。

    您遇到的问题是因为您正在尝试比较字符串。
    Date() 返回字符串,据我所知,没有一种编程语言可以正确地(无论在这种情况下的正确含义)将 > 或

    所以在比较中使用 Unix 时间,因为它是数字并且更容易让计算机理解。

    $now = strtotime('now');
    $start = strtotime('1 January 2021');
    $end = strtotime('31 January 2021');
    
    if ($now >= $start && $now <= $end):
        echo 'true';
    else:
        echo 'false';
    endif;
    

    https://3v4l.org/KAvQ2

    【讨论】:

      【解决方案2】:

      date('d/m/y') 给你一个类似30/11/20 的字符串。以这种格式比较日期实际上意味着您在比较字符串,这仅在日期为 YYYYMMDD(或 YYYY-MM-DD)格式时才有效。

      使用strtotime() 将类似英语的日期转换为 Unix 时间戳(只是一个大整数)并直接比较它们要容易得多:

      if ( 
          strtotime('now') >= strtotime('1 January 2021')
              &&
          strtotime('now') <= strtotime('31 January 2021')
      ) {
          echo 'true';
      } else {
          echo 'false';
      }
      

      【讨论】:

      • 此答案已在 15 分钟前发布。
      【解决方案3】:

      您确实应该使用DateTime 类进行所有与日期相关的计算。不要使用旧的strtotime()date(),除非你真的知道自己在做什么。

      使用DateTime 类真的很简单:

      <?php
      
      $start = new DateTime('1 January 2021');
      $end = new DateTime('31 January 2021');
      $today = new DateTime();
      if($today >= $start && $today <= $end){
          echo 'In between';
      } else {
          echo 'outside or range';
      }
      

      Demo

      【讨论】:

        【解决方案4】:

        用以下代码替换您的代码。

        if (strtotime(date('d/m/y', strtotime('now'))) >= strtotime(date('d/m/y', strtotime('1 January 2021'))) && strtotime(date('d/m/y', strtotime('now'))) <= strtotime(date('d/m/y', strtotime('31 January 2021')))):
            echo 'true';
        else:
            echo 'false';
        endif;
        

        【讨论】:

        • @Sachin J 将其更改为 2020 年 11 月 1 日和 2021 年 1 月 31 日将不起作用,这应该返回 true - 但不......我很困惑!
        • 为什么要把字符串日期转换成Unix时间,把Unix时间转换成字符串,然后再把字符串转换成Unix时间。
        • @Andreas 这是一种 CRC 技术。
        • @MarkusAO 如果是这种情况,那么我建议使用一种不改变值的格式。 3v4l.org/0G8Ko
        • @Andreas 我会亲自添加一个例程,该例程记录每次不必要地来回转换的值的哈希值,最后将哈希值转换为二进制并将它们相加并除以零以确保零错误。
        猜你喜欢
        • 2023-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多