Re: getting date - howto
| From: | Billy Harvey | Date: | Sat, 01 Jul 2000 17:17:51 +0000 |
| Subject: | Re: getting date - howto | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-4274@lists.php.net to get a copy of this message | ||
spoon fork writes:
> Hi,
>
> Is there any functions in PHP that I can use to, say,
> determine on what date the first, second, third or fourth Monday
> (or any weekday) is on a particular month?
>
> Mucho gracias in advance,
>
> --mel
I didn't know of one, so my (learning programming early) son and I
worked this up this morning as a programming exercise. The limited
testing I gave it seems ok, but feel free to email me if it's not
clear. There's a test case at the bottom for the second Saturday of
Jul 2000 (the date Harry Potter arrives, so it's of keen interest to
my son :).
Billy
<?
function dow2($year, $month, $day) {
// returns 0 for Sunday through 6 for Saturday for a given
// year, month, and date
if ($month < 3) {
$year = $year - 1 ;
$month = $month + 12;
}
$dow2 = ($day + (153 * $month - 457) / 5 + floor(365.25 * $year) - floor($year * .01) +
floor($year * 0.0025) + 2) % 7;
if ($dow < 0) {
$dow = $dow + 7;
}
return $dow2;
}
function dow($year, $month, $day, $count) {
// returns for year and month the date for the count of the day,
// where 0 is Sunday and 6 is Saturday for the day
// returns 0 if nonexistant (ex: the 6th Saturday of a month)
// ex: dow2(2000,7,2,6) returns the date of the 2nd Saturday of Jul 2000 as 8
$count--;
$times_looped = 0;
$test_date = 1;
$returned_day = dow2($year, $month, $test_date);
while ($returned_day != $day or $times_looped != $count) {
if ($returned_day == $day) {
$times_looped++;
}
$test_date++;
$returned_day = dow2($year, $month, $test_date);
}
// test for a valid date
$a=array(31,29,31,30,31,30,31,31,30,31,30,31);
if ($year % 4 != 0) {
$a[1] = 28;
} else {
if ($year % 400 == 0) {
$a[1] = 29;
} else {
if ($year % 100 == 0) {
$a[1] = 28;
}
}
}
if ($a[$month - 1] < $test_date) {
$test_date = 0;
}
return $test_date;
}
$y = 2000;
$m = 7;
$d = 6;
$c = 2;
echo dow($y,$m,$d,$c);
?>