我想用PHP创建一个脚本,搜索从现在到一年后的所有日期,并列出每个星期五和星期六的日期。我尝试使用PHP的date()和mktime()函数,但无法想出如何实现。这可行吗?
谢谢, Ben
谢谢, Ben
以下是一种酷炫的方法,特别感谢strtotime
的相对格式。
$friday = strtotime('Next Friday', time());
$saturday = strtotime('Next Saturday', time());
$friday = strtotime('+1 Week', $friday);
$saturday = strtotime('+1 Week', $saturday);
当然你应该调整它来做你想要的事,但这与我试图说明的重点无关。 此外,请注意strtotime
将给出时间戳。 要查找日期,请使用:date('Y-m-d', $friday)
还需要知道的是,Next <dayofweek>
将会排除当前日期进行搜索,如果你希望包括当前日期,可以这样做:
$friday = strtotime('Next Friday', strtotime('-1 Day', time()));
以下是一个完整的可行脚本,可以实现你所需的功能。
<?php
// prevent multiple calls by retrieving time once //
$now = time();
$aYearLater = strtotime('+1 Year', $now);
// fill this with dates //
$allDates = Array();
// init with next friday and saturday //
$friday = strtotime('Next Friday', strtotime('-1 Day', $now));
$saturday = strtotime('Next Saturday', strtotime('-1 Day', $now));
// keep adding days untill a year has passed //
while(1){
if($friday > $aYearLater)
break 1;
$allDates[] = date('Y-m-d', $friday);
if($saturday > $aYearLater)
break 1;
$allDates[] = date('Y-m-d', $saturday);
$friday = strtotime('+1 Week', $friday);
$saturday = strtotime('+1 Week', $saturday);
}
//XXX: debug
var_dump($allDates);
?>
祝你好运,Alin
define('FRIDAY', 5);
define('SATURDAY', 6);
$from = new DateTimeImmutable();
$to = new DateTimeImmutable('+1 year');
for ($date = $from; $date < $to; $date->modify('+1 day')) {
switch ($date->format('w')) {
case FRIDAY:
case SATURDAY:
echo $date->format('r') . PHP_EOL;
}
}
在 PHP/5.5.0 之前,您必须使用常规的 DateTime
类并进行克隆:
$from = new DateTime();
$to = new DateTime('+1 year');
for ($date = clone $from; $date < $to; $date->modify('+1 day')) {
switch ($date->format('w')) {
case FRIDAY:
case SATURDAY:
echo $date->format('r') . PHP_EOL;
}
}
$secondsperday=86400;
$firstdayofyear=mktime(12,0,0,1,1,2010);
$lastdayofyear=mktime(12,0,0,12,31,2010);
$theday = $firstdayofyear;
for($theday=$firstdayofyear; $theday<=$lastdayofyear; $theday+=$secondsperday) {
$dayinfo=getdate($theday);
if($dayinfo['wday']==5 or $dayinfo['wday']==6) {
print $dayinfo['weekday'].' '.date('Y-m-d',$theday)."<br />";
}
}
$number_of_days_from_now = 365;
$now = time();
$arr_days = array();
$i = 0;
while($i <> $number_of_days_from_now){
$str_stamp = "- $i day";
$arr_days[] = date('Y-m-d',strtotime($str_stamp,$now));
$i ++;
}
var_dump($arr_days);
我做了类似于被接受的答案的事情,但这并不适合我