Working days (Mon-Fri) in PHP
Is there a way to use strtotime开发者_运维知识库
to add working days (Monday to Friday) to a date? Or some other method? What I want to do is:
date ( 'Y-m-j' , strtotime ( '+3 working days' ) )
If you are limiting to weekdays use the string weekdays.
echo date ( 'Y-m-j' , strtotime ( '3 weekdays' ) );
This should jump you ahead by 3 weekdays, so if it is Thursday it will add the additional weekend time.
Source: http://www.php.net/manual/en/datetime.formats.relative.php
I have found this buggy when needing a larger amount of weekdays. I was looking for X amount of business days after the 1st of the current month.
Looked great at first until after adding > 5 business days (similar to what @zerkms found).
This has proved more accurate for me.
function _getBusinessDayOfMonth( $days ) {
$time = strtotime(date("m/1/Y 00:00")); //finding # of business days after 1st of the month
$i = 0; //start with zero
while ($i < $days) { //loop through until reached the amount of weekdays
$time = strtotime("+1 day", $time); //Increase day by 1
if (date("N", $time) < 6) { //test if M-F
$i++; //Increase by 1
}
}
echo date("m/d/Y", $time);
}
For PHP >= 5.6
public function addWorkingDays($date, $day)
{
if (!($date instanceof \DateTime) || is_string($date)) {
$date = new \DateTime($date);
}
if ($date instanceof \DateTime) {
$newDate = clone $date;
}
if ($day == 0) {
return $newDate;
}
$i = 1;
while ($i <= abs($day)) {
$newDate->modify(($day > 0 ? ' +' : ' -') . '1 day');
$next_day_number = $newDate->format('N');
if (!in_array($next_day_number, [6, 7])) {
$i++;
}
}
return $newDate;
}
You can do this too:
echo date_create()->modify("+3 weekdays")->format("Y-m-d");
See:
https://www.php.net/manual/en/function.date-create.php
https://www.php.net/manual/en/datetime.modify.php
I think a function can be easily developed that you can just export current day no of the week and you can add two and mod of 5 will give you easily weekday.
function increaseWorkDay($workDayToProcess, $dayToAdd){
if($workDayToProcess >= 4 && $workDayToProcess <= 6){
$workDayToProcess= 4;
}
$workDayToProcess+= $dayToAdd;
return $workDayToProcess % 5;
}
And you can export the weekday name by using an array, this method can alternatively be used.
I do it recursively, worked for me
function add_work_days($date, $day){
if($day == 0)
return $date;
$date->add(new DateInterval('P1D'));
if(!in_array($date->format('N'), array('6', '7')))
$day--;
return add_work_days($date, $day);
}
$date = add_work_days(new DateTime(), 3);
echo $date->format('d/m/Y');
For older versions of PHP < 5.3
function AddWorkingDays($startDate, $adddays)
{
$retdate = $startDate;
$sign = "+";
if($adddays < 0){
$adddays = $adddays*-1;
$sign = "-";
}
while ($adddays > 0) {
$retdate = date ( 'Y-m-d' , strtotime ( "$retdate {$sign}1 day" ) );
$what_day = date("N", strtotime($retdate));
if ( $what_day != 6 && $what_day != 7 ) // 6 and 7 are weekend
$adddays--;
};
return $retdate;
}
精彩评论