Reputation: 1451
I want to check if there is any sat or sun between two dates in php.
$fromDate = '03/21/2016';
$toDate = '03/28/2016';
I've tried other solution asked here but they didn't worked well. I want it in laravel 5.2 so if there is any easy way to handle this please guide me. thanks!
Update i also want to get if there is weekday(mon-fri) between two dates. i need it because user can select sat and Sunday only so in this condition I've to hide weekday option from him. So what I need is a method which tells me if start and end date has weekend or weekdays or both in it.
Upvotes: 1
Views: 3447
Reputation: 2722
Refined version of @FastTurtle answer that I ended up using. The main change being that the loop is ended if a weekend is found along with some other efficiency improvements.
$is_weekend = false;
$fromDate = strtotime('2016-03-21');
$toDate = strtotime('2016-03-28');
// Loop through each day until the end date is reached
while ($fromDate <= $toDate) {
$dayOfWeek = date("w", $fromDate);
// Check if it's a weekend (0 = Sunday, 6 = Saturday)
if ($dayOfWeek == 0 || $dayOfWeek == 6) {
$is_weekend = true;
break; // Exit loop if weekend is found
}
// Move to the next day
$fromDate = strtotime("+1 day", $fromDate);
}
Upvotes: 0
Reputation: 3002
You can use date("N")
to get the current day of the week and add the difference of days between your dates... If this is bigger or equal to 6 than it's a weekend between or one date is in the weekend.
//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
}
Upvotes: 3
Reputation: 1787
try
<?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;
hoe it helps :)
Upvotes: 2