2

I want to subtract $date with $interval, please note that $interval is number of workdays. Here are some examples (format: yyyy-mm-dd)

  • $date = 2013-10-07, $interval = 5, $result = 2013-09-30
  • $date = 2013-10-07, $interval = 1, $result = 2013-10-04

My code so far

$div = floor($interval / 5);
$mod = $interval % 5;
$workdays = $div * 7 + $mod;
$result = date("Y-m-d", strtotime($date . "-$workdays days"));
  • $date = 2013-10-07, $interval = 5, $result = 2013-09-30 => true
  • $date = 2013-10-07, $interval = 1, $result = 2013-10-06 => false

Please give me direction to solve this problem, thanks.

shankshera
  • 947
  • 3
  • 20
  • 45
  • if you just want to skip saturdays and sundays then you can build a simple function that checks the date. But if you want to take into account also holidays then it's more complicated. Look at this discussion if it can help http://stackoverflow.com/questions/336127/calculate-business-days – arilia Oct 07 '13 at 09:25

2 Answers2

2

If you define your workdays as MON-FRI then all you need to do is use the weekdays keyword of strtotime. Resulting in something like strtotime("-7 weekdays") which will exclude saturdays and sundays.

Or following your code:

$workdays = 5;
$result = date("Y-m-d", strtotime($date . "-$workdays weekdays"));

Issues with this answer

https://bugs.php.net/bug.php?id=63521

Juan Cortés
  • 20,634
  • 8
  • 68
  • 91
1

Use example:

var_dump( subtractWorkDays('2013-10-07', 5) ); # 2013-09-30
var_dump( subtractWorkDays('2013-10-07', 1) ); # 2013-10-04

Function:

function subtractWorkDays($date, $days) {
    return date_create($date)->modify("-$days weekdays")->format('Y-m-d');
}
Glavić
  • 42,781
  • 13
  • 77
  • 107