[英]How to check if there is a weekend between two dates in php?
我想檢查php中兩個日期之間是否有sat或sun。
$fromDate = '03/21/2016';
$toDate = '03/28/2016';
我試過這里提出的其他解決方案,但效果不佳。 我希望它在 laravel 5.2 中,所以如果有任何簡單的方法來處理這個問題,請指導我。 謝謝!
更新我也想知道兩個日期之間是否有工作日(周一至周五)。 我需要它,因為用戶只能選擇周六和周日,所以在這種情況下我必須向他隱藏工作日選項。 所以我需要的是一種方法,它告訴我開始和結束日期是否包含周末或工作日或兩者都包含在內。
您可以使用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
}
試試
<?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;
鋤頭有幫助:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.