获取两个日期之间的不同日期(不包括周末)

时间:2019-03-03 13:28:18

标签: php date mysqli datediff

我试图从数据库中获取两个日期之间的天数。 Date_from和Date_to。而且我遇到了错误。任何帮助,将不胜感激。 代码:

<?php
    require('config/conn.php');

    // Select all from table 'reguests'
    $query = 'SELECT * FROM requests';

    //Results from table
    $result = mysqli_query($conn, $query);

    //Fetch data
    $requests = mysqli_fetch_all($result, MYSQLI_ASSOC);

    //Free result from fetch
    mysqli_free_result($result);

    //Get Days Count Between Dates From And To
    $dateFrom = $request['date_from'];
    $dateTo = $requests['date_to'];

    $daysDiff = floor(abs(strtotime($dateTo) - strtotime($dateFrom)) / (60*60*24));


    //Close conn
    mysqli_close($conn);
    ?>

输出:

<td><?php echo $daysDiff ?>

2 个答案:

答案 0 :(得分:1)

您的问题标题说排除周末,但是您的代码似乎没有尝试?

要考虑类似这样的更复杂的逻辑,计算周期并用它在几天内进行迭代可能是明智的。

类似这样的东西:

$dateFrom = new DateTime();
$dateTo   = new DateTime( '+1 month +1 second' ); // Add 1s so period includes last day.

$period   = new DatePeriod( $dateFrom, new DateInterval( 'P1D' ), $dateTo );
$days     = 0;

foreach ( $period as $date ) {

    $day = $date->format( 'l' );

    if ( 'Saturday' !== $day && 'Sunday' !== $day ) {
        $days ++;
    }
}

echo $days; // 23

答案 1 :(得分:0)

请检查您的标题,该标题与您的问题不明确。但是要检查日期之间的差异,请查看链接上的Php手册:http://php.net/manual/en/datetime.diff.php

如果您真的想检查一天是否是周末,请检查:Checking if date is weekend PHP