note 69502 deleted from function.strtotime by derick
| From: | derick@php.net | Date: | Sun, 24 Sep 2006 11:40:48 +0000 |
| Subject: | note 69502 deleted from function.strtotime by derick | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-117494@lists.php.net to get a copy of this message | ||
Note Submitter: drew at drew dot plznospam dot co dot il
----
In my current project, I had the need for strtotime to calculate dates in the near past and future,
only to use business days (i.e. skip weekends) so I wrote a wrapper function that will use strtotime
but if the resulting date is a weekend or holiday it will keep going back or forward.
Basically I needed "strtotime('-2 days')" to go back to Friday if I called it on
a Tuesday (since 2 days ago was Sunday).
This makes use of the getHolidays function written by codepanda at yahoo dot com and submitted on
24-Aug-2005, so special thanks for that. I am unable to include it w/out the site complaining my
message is too long.
<?php
/**
* Converts a string to timestamp, skipping weekends and holidays if applicable
* For example if today is Tuesday, strtotime_bizdays('-2 days'); returns the previous
Friday since it first lands on Sunday
* The function will check for holidays and recurse on itself if skipping weekends lands on a
holiday, or vice versa.
*
* @author "Drew Phillips" <drew at drew dot co dot il>
* @param string $str The date string to convert
* @param int $now The timestamp representing the current time
* @return int The timestamp of the calculated date
*/
function strtotime_bizdays($str, $now = null)
{
static $holidays = array(); //keep it around to speed up more than 1 call
if ($now == null) $now = time();
$year = date('Y', $now);
if (!array_key_exists($year, $holidays)) //dont have the holidays for this year yet, get em
$holidays[$year] = getHolidays($year);
$time = strtotime($str, $now);
if ($time < $now) //looks like the $str references the past
$sign = '-';
else //future
$sign = '+';
if ( (date('w', $time) == 0 && $sign == '+') || (date('w',
$time) == 6 && $sign == '-') ) //Sun going forward || Sat going back
$time = strtotime("+1 day", $time);
else if ( date('w', $time) == 0 && $sign == '-' ) //Sun going back
$time = strtotime("-2 days", $time);
else if ( date('w', $time) == 6 && $sign == '+' ) //Sat going forward
$time = strtotime("+2 day", $time);
$key = date('Y-m-d', $time); //array key for holiday
$year = date('Y', $time); //year for checking if we changed years
if (!array_key_exists($year, $holidays)) //moved into another year
$holidays[$year] = getHolidays($year);
if (array_key_exists($key, $holidays[$year])) { //we're on a holiday
if ($sign == '+') {
$time += 86400;
} else {
$time -= 86400;
}
$time = strtotime_bizdays( date('Y-m-d H:i:s', $time) ); //check in case moving off
the holiday hit a weekend
}
return $time;
}
?>