【问题标题】:How to check if there is a weekend between two dates in php?如何检查php中两个日期之间是否有周末?
【发布时间】:2016-07-07 20:22:15
【问题描述】:

我想检查 php 中两个日期之间是否有星期六或太阳。

$fromDate = '03/21/2016';
$toDate = '03/28/2016';

我尝试过这里提出的其他解决方案,但效果不佳。我想在 laravel 5.2 中使用它,所以如果有任何简单的方法来处理这个问题,请指导我。谢谢!

更新 我也想知道两个日期之间是否有工作日(周一至周五)。我需要它,因为用户只能选择周六和周日,所以在这种情况下,我必须向他隐藏工作日选项。所以我需要一个方法来告诉我开始和结束日期是否有周末或工作日或两者都有。

【问题讨论】:

    标签: php date datetime laravel-5.2


    【解决方案1】:

    您可以使用date("N") 获取星期几并添加日期之间的天数差...如果这大于或等于 6,则它是一个周末或一个日期在周末。

    //Get current day of week. For example Friday = 5
    $day_of_week = date("N", strtotime($fromDate));
    
    $days = $day_of_week + (strtotime($toDate) - strtotime($fromDate)) / (60*60*24);
    //strtotime(...) - convert a string date to unixtimestamp in seconds.
    //The difference between strtotime($toDate) - strtotime($fromDate) is the number of seconds between this 2 dates. 
    //We divide by (60*60*24) to know the number of days between these 2 dates (60 - seconds, 60 - minutes, 24 - hours)
    //After that add the number of days between these 2 dates to a day of the week. So if the first date is Friday and days between these 2 dates are: 3 the sum will be 5+3 = 8 and it's bigger than 6 so we know it's a weekend between.
    
    
    
    if($days >= 6){
      //we have a weekend. Because day of week of first date + how many days between this 2 dates are greater or equal to 6 (6=Saturday)
    } else {
      //we don't have a weekend
    }
    

    【讨论】:

    • 成功了。谢谢!你能解释一下它的工作原理吗,这样我也能理解这里发生了什么。
    • 我有一个问题,您的解决方案会告诉您两个日期之间是否有周末。如果我想知道两个日期之间是否有工作日(周一至周五)怎么办?我需要它,因为用户只能选择周六和周日,所以在这种情况下我必须向他隐藏工作日选项。
    • @UmairMalik 我用 cmets 更新了我的答案,这样你就可以更好地理解它的作用。如果有不清楚的地方请告诉我。
    【解决方案2】:

    试试

    <?php
        $is_weekend = 0;
        $fromDate = strtotime('2016-03-21');
        $toDate = strtotime('2016-03-28');
        while (date("Y-m-d", $fromDate) != date("Y-m-d", $toDate)) {
            $day = date("w", $fromDate);
            if ($day == 0 || $day == 6) {
                $is_weekend = 1;
            }
            $fromDate = strtotime(date("Y-m-d", $fromDate) . "+1 day");
        }
        echo $is_weekend;
    

    它有帮助:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-07
      相关资源
      最近更新 更多