Initially I am trying to create a function to display how many times does a specific day fall into particular date. for example how many times does Saturday fall into January 1st of certain year to certain year.
<?php
$firstDate = '01/01/2000';
$endDate = '01/01/2012';
$newYearDate= '01/01';
# convert above string to time
$time1 = strtotime($firstDate);
$time2 = strtotime($endDate);
$newYearTime = strtotime($newYearDate);
for($i=$time1; $i<=$time2; $i++){
$saturday = 0;
$chk = date('D', $newYearTime); #date conversion
if($chk == 'Sat' && $chk == $newYearTime){
$saturday++;
}
}
echo $saturday;
?>
You can only have a saturday to be in, say January 1, once in a year, so:
$firstDate = '01/01/2000';
$endDate = '01/01/2012';
$time1 = strtotime($firstDate);
$time2 = strtotime($endDate);
$saturday = 0;
while ($time1 < $time2) {
$time1 = strtotime(date("Y-m-d", $time1) . " +1 year");
$chk = date('D', $time1);
if ($chk == 'Sat') {
$saturday++;
}
}
echo "Saturdays at 01/01/yyyy: " . $saturday . "\n";
The line I changed was:
$time1 = strtotime(date("Y-m-d", strtotime($time1)) . " +1 year");
to
$time1 = strtotime(date("Y-m-d", $time1) . " +1 year");
as $time1
is already in seconds from the epoch -- the format required for date.
strtotime
gives you seconds since 1970-01-01. Since you're interested in days only, you can increment your loop by 86400 seconds per day to speed up your calculation
for($i = $time1; $i <= $time2; $i += 86400) {
...
}
There are several points
$saturday
out of your loop $i
instead of $newYearTime
This should work
$firstDate = '01/01/2000';
$endDate = '01/01/2012';
# convert above string to time
$time1 = strtotime($firstDate);
$time2 = strtotime($endDate);
$saturday = 0;
for($i=$time1; $i<=$time2; $i += 86400){
$weekday = date('D', $i);
$dayofyear = date('z', $i);
if($weekday == 'Sat' && $dayofyear == 0){
$saturday++;
}
}
echo "$saturday\n";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.