我正在尝试使用 PHP 创建一个脚本,用于搜索从现在到一年内的所有日期,并列出周五和周六的所有日期。我试图使用 PHP 的 date() 和 mktime() 函数,但想不出一种方法来做到这一点。可以吗?
谢谢, 本
这是如何以一种很酷的方式做到这一点,特别感谢
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);
?>
祝你好运,阿林
使用 DateTime 对象(演示):
define('FRIDAY', 5);
define('SATURDAY', 6);
$from = new DateTimeImmutable();
$to = new DateTimeImmutable('+1 year');
for ($date = $from; $date < $to; $date = $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);
我做了一些类似于已接受的答案但不适合我的事情