【问题标题】:Getting the Date and numeric weekday in PHP在 PHP 中获取日期和数字工作日
【发布时间】:2017-03-25 10:38:18
【问题描述】:

我正在用 PHP 开发一个应用程序,我需要使用日期和工作日的数字表示。

我尝试了以下方法:

$today = date("Y-m-d");
$number = date('N', strtotime($today));
echo "Today: " . $today . " weekday: " . $number . "<br>";
$today = strtotime($today);
$tomorrow = strtotime($today);
$tomorrow = strtotime("+1 day", $today);
$number2 = date('N', strtotime($tomorrow));
echo "Tomorrow: " . date('Y-m-d', $tomorrow) . " weekday: " . $number2 . "<br>";

输出

Today: 2016-11-11 weekday: 5
Tomorrow: 2016-11-12 weekday: 4

这是不对的,因为明天的工作日应该是 6 而不是 4。

有人可以帮帮我吗?

【问题讨论】:

    标签: php date datetime dayofweek weekday


    【解决方案1】:

    使用DateTime 将提供一个简单的解决方案

    <?php
    $date = new DateTime();
    echo 'Today: '.$date->format( 'Y-m-d' ) .' weekday '. $date->format( 'N' )."\n";
    $date->modify( '+1 days' );
    echo 'Tomorrow: '.$date->format( 'Y-m-d' ) .' weekday '. $date->format( 'N' )."\n";
    

    输出

    Today: 2016-11-11 weekday 5
    Tomorrow: 2016-11-12 weekday 6
    

    但是天数略有不同,N 表示工作日数,如您所见,星期五(今天)显示为 5。星期一将是 1,星期日是 7。

    如果您查看下面的示例,您应该会得到相同的结果

    echo date( 'N' );
    

    输出

    5
    

    日期格式 - http://php.net/manual/en/function.date.php

    【讨论】:

    • 我认为这是最好的答案,因为它展示了如何在 date 之前使用 DateTime,这对于 PHP 社区的发展非常重要。
    【解决方案2】:

    您的代码几乎没有错误,这是有效的:

    $today = date("Y-m-d");
    $number = date('N', strtotime($today));
    echo "Today: " . $today . " weekday: " . $number . "<br>";
    
    $today = strtotime($today);
    $tomorrow = strtotime($today);
    $tomorrow = strtotime("+1 day", $today);
    $number2 = date('N', $tomorrow);
    echo "Tomorrow: " . date('Y-m-d', $tomorrow) . " weekday: " . $number2 . "<br>";
    

    【讨论】:

      【解决方案3】:

      DateTime 是 PHP 中处理日期的面向对象的方法。我发现它工作得更流畅。除此之外,它看起来好多了。

      // Create a new instance
      $now = new DateTime();
      echo $now->format('N');
      
      // Next day
      $now->modify('+1 day');
      echo $now->format('N');
      

      资源

      【讨论】:

        【解决方案4】:

        你几乎说对了,但并不完全正确。你为什么在$number2 上使用strtotime?将其更改为$number2 = date('N', $tomorrow); 即可。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-12-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-03-11
          • 1970-01-01
          相关资源
          最近更新 更多