I am trying to format only the working days, removing Saturday, Sunday and holidays.
I found this function "function day_holiday()" in the "Stackoverflow" on holidays in my home country.
I created this script in php below in my knowledge
//-------------------------HOLIDAY--------------
function day_holiday($ano = null){
if ($ano === null){
$ano = intval(date('Y'));
}
$pascoa = easter_date($ano);
$dia_pascoa = date('j', $pascoa);
$mes_pascoa = date('n', $pascoa);
$ano_pascoa = date('Y', $pascoa);
$holiday = array(
mktime(0, 0, 0, 1, 1, $ano),
mktime(0, 0, 0, 4, 21, $ano),
mktime(0, 0, 0, 5, 1, $ano),
mktime(0, 0, 0, 9, 7, $ano),
mktime(0, 0, 0, 10, 12, $ano),
mktime(0, 0, 0, 11, 2, $ano),
mktime(0, 0, 0, 11, 15, $ano),
mktime(0, 0, 0, 12, 25, $ano),
mktime(0, 0, 0, $mes_pascoa, $dia_pascoa - 48, $ano_pascoa),
mktime(0, 0, 0, $mes_pascoa, $dia_pascoa - 47, $ano_pascoa),
mktime(0, 0, 0, $mes_pascoa, $dia_pascoa - 2 , $ano_pascoa),
mktime(0, 0, 0, $mes_pascoa, $dia_pascoa , $ano_pascoa),
mktime(0, 0, 0, $mes_pascoa, $dia_pascoa + 60, $ano_pascoa),
);
sort($holiday);
return $holiday;
}
//-------------------------HOLIDAY--------------
//-------------SCRIPT-------------
function formatDate($startDate,$days) {
$holiday = day_holiday();
foreach ($holiday as $allholiday){
if($startDate==date('d-m-Y',$allholiday)){
$newDate=date('d-m-Y', strtotime("+1 days",strtotime($startDate)));
}else{
$newDate = date('d-m-Y', strtotime("{$startDate} +{$days} weekdays"));
}
}
return $newDate;
}
$sales = "19-01-2019"; //19 and Saturday is jumping for Monday 21 second
/*
These are some holidays.
01-01-2019
04-03-2019
05-03-2019
19-04-2019
21-04-2019
21-04-2019
01-05-2019
*/
echo "Start: ",date("d-m-Y", strtotime($sales)),"<br />";
echo formatDate($sales, "0");
The problem is removing only on Saturdays and Sundays. The holidays are not being removed. What is missing? can someone help me? If you have a more dynamic script you could post here.
This is probably a more robust way of doing what you want. The function creates a DateTime
object from the start time, then compares the timestamp to see if
$holiday
array; or If none of these conditions are true, the loop exits and the date is returned. Otherwise, the date is incremented by 1 day until a date is found that matches all the conditions (ie Monday to Friday, and not a holiday).
function formatDate($startDate) {
$holiday = day_holiday();
$start = date_create_from_format('d-m-Y H:i:s', $startDate . ' 00:00:00');
do {
$ts = (int)$start->format('U');
$dow = (int)$start->format('w');
if (!in_array($ts, $holiday) && $dow != 0 && $dow != 6) break;
$start->modify('+1 day');
}
while (true);
return $start->format('d-m-Y');
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.