如何使用PHP列出一年中的所有日期?

时间:2010-10-28 16:09:59

标签: php date mktime

我正在尝试使用PHP创建一个脚本,搜索从现在到一年的所有日期,并列出星期五和星期六的所有日期。我试图使用PHP的date()和mktime()函数,但无法想到这样做的方法。有可能吗?

谢谢, 本

4 个答案:

答案 0 :(得分:9)

以下是如何以一种很酷的方式做到这一点,特别感谢strtotime的{​​{3}}。

$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

答案 1 :(得分:4)

使用DateTime对象:

<?php

define('FRIDAY', 5);
define('SATURDAY', 6);

$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;
    }
}

更新:我添加了$date=clone $from部分,注意PHP / 5中的对象不再与=运算符一起复制,而是被引用。

答案 2 :(得分:1)

$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 />";
    }
}

答案 3 :(得分:1)

    $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);

我做了类似于不适合我的公认答案

相关问题