2010-10-28 35 views
8

我正在嘗試使用PHP創建一個腳本,用於搜索現在和一年之間的所有日期,並列出星期五和星期六的所有日期。我試圖使用PHP的date()和mktime()函數,但無法想到這樣做的方法。可能嗎?如何使用PHP列出一年中的所有日期?

感謝, 本

回答

9

下面是如何做一個冷靜的方式,並特別感謝strtotimerelative formats

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

?> 

祝你好運,阿林

+0

基準東西:〜0.011s – 2010-10-28 16:40:28

+0

謝謝阿林,這只是在我一直在尋找!絕對的輝煌! – Ben 2010-11-01 11:06:54

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

使用86400的計算理所當然地認爲所有日子都有24小時,但情況並非總是如此。由於夏令時,下個星期六在西班牙有25個小時。 – 2010-10-28 16:37:58

+0

基準:〜0.006s – 2010-10-28 16:41:18

+0

另請注意,世界各地的夏令時規則差異很大。這就是爲什麼在操縱時間時應該使用內置的語言功能。 – 2010-10-28 16:46:43

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不再複製與=運營商,但引用。

+0

基準:〜0.006s – 2010-10-28 16:40:47

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

我做類似接受的答案是不適合我

相關問題