Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working days (Mon-Fri) in PHP

Tags:

php

strtotime

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' ) ) 
like image 221
fredley Avatar asked Nov 23 '10 21:11

fredley


People also ask

How does PHP calculate working days?

php function AddWorkDays(){ $i = 0; $d = 5; // Number of days to add while($i <= $d) { $i++; if(date('N', mktime(0, 0, 0, date(m), date(d)+$i, date(Y))) < 5) { $d++; } } return date(Y).

How can I get Monday of current week in PHP?

Try this. echo date('Y-m-d', strtotime('last monday', strtotime('next monday'))); It will return current date if today is monday, and will return last monday otherwise.

How do I get the day of the week in PHP?

Use strtotime() function to get the first day of week using PHP. This function returns the default time variable timestamp and then use date() function to convert timestamp date into understandable date. strtotime() Function: The strtotime() function returns the result in timestamp by parsing the time string.

How can get first and last day of month in PHP?

php $dt = "2008-02-23"; echo 'First day : '. date("Y-m-01", strtotime($dt)). ' - Last day : '. date("Y-m-t", strtotime($dt)); ?>


2 Answers

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

like image 166
John Giotta Avatar answered Sep 17 '22 12:09

John Giotta


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);     } 
like image 29
mpickens Avatar answered Sep 20 '22 12:09

mpickens