Using Date () to calculate three business days ago?

I want to get the PHP date within three business days ago.

I found many examples of getting dates with all kinds of text methods, but the closest I found this one , but it returns three dates (not one date, three days ago) and requires the get_holidays function, for which the code was not provided.

How can I write PHP code that will be returned three business days before today?

This works, but does not take into account the days of the week / days off:

date('Ym-d', strtotime('-3 days')); // returns 2012-12-01 

This does not work, but this is what I would like to see:

 date('Ym-d', strtotime('four week days ago')); 

Actually the above returns "1969-12-31". How to do it: strtotime('-4 week days') .

+4
source share
5 answers

You can just continue the day ago until you get what you want. I'm not sure if this is the most efficient way, but it does its job:

 $count = 0 $day = strtotime('-1 day'); while ($count < 3 || date('N', $day) > 5) { $count++; $day = strtotime('-1 day', $day); } 
+10
source

FINAL ANSWER:

For beginners like me, this was working code using the Explosion Pills answer:

 function working_days_ago($days) { $count = 0; $day = strtotime('-1 day'); while ($count < $days || date('N', $day) > 5) { $count++; $day = strtotime('-1 day', $day); } return date('Ym-d', $day); } $three_days_ago = working_days_ago('3'); 

It works like a charm!

+1
source

I was getting unexpected results from the above functions, so I wrote this. Arguments are the number of days, forward (1) or backward (0) and date. If the date is not indicated for today, the following will be used:

 // returned $date Y/m/d function work_days_from_date($days, $forward, $date=NULL) { if(!$date) { $date = date('Ym-d'); // if no date given, use todays date } while ($days != 0) { $forward == 1 ? $day = strtotime($date.' +1 day') : $day = strtotime($date.' -1 day'); $date = date('Ym-d',$day); if( date('N', strtotime($date)) <= 5) // if it a weekday { $days--; } } return $date; } 
0
source

3 days ago from today:

 $date = new DateTime(); $date->sub(new DateInterval('P3D')); echo $date->format('Ym-d') . "\n"; 

3 days ago from a specific date:

 $date = new DateTime('2000-01-20'); $date->sub(new DateInterval('P3D')); echo $date->format('Ym-d') . "\n"; 
0
source

get the day after function ↓

 function working_days($days){ $day = strtotime(date('Ym-d')); for ($x=0;$x<$days;$x++) { $day = strtotime('+1 day', $day); if (date('N', $day) > 6) { $x = $x - 1; } } return date('Ym-d',$day); } print_r( working_days(25)); } 
-1
source

All Articles