2011-10-04 24 views
0

這些答案一個月中日期的最後一天的名單不太做我想做的:獲取在PHP

Getting last month's date in php How to find the last day of the month from date?

我有下面的代碼,是爲了打印一個選擇框從給定日期的月份日期的所有最後一天:

  $last_case_date = $this->query_end_date(); 
      $increm_date = "2011-06-01"; 

      echo '<select name = "end_interval">'; 
      $increm_date = date('Y-m-d', strtotime("$increm_date")); 
      while($increm_date <= $last_case_date) { 
       // next date is $increm_date + 1 month 
       $increm_date = date('Y-m-d', strtotime("$increm_date + 1 months")); 
       // then we want the last day of this new date 
       $month = substr($increm_date, 5, 2); 
       $year = substr($increm_date, 0, 4); 
       $increm_date = $this->last_day_of_month($month, $year); 
       echo '<option value = "'.$increm_date.'" selected = "selected"'.'>'.$increm_date.'</option>'; 
      } 
      echo '</select>'; 

其中last_day_of_month是這樣的:

function last_day_of_month($month = '', $year = '') { 
     if(empty($month)) { 
      $month = date('m'); 
     } 
     if(empty($year)) { 
      $year = date('Y'); 
     } 
     $result = strtotime("{$year}-{$month}-01"); 
     $result = strtotime('-1 second', strtotime('+1 months', $result)); 
     return date('Y-m-d', $result); 
    } 

我從here借來的。

出現這種情況奇怪的是,我得到這些日期:

2011-07-31 2011-08-31 2011-10-31

但沒有2011-09-30!這可能與9月份只有30天的事情有關嗎?

任何人都可以發現問題嗎?我一直盯着它很長一段時間....謝謝你:)。

回答

2

你可以只使用內置的功能爲PHP

date('t', $timestamp); 

所以你的函數看起來像:

function last_day_of_month($month = '', $year = '') { 
    $month 
     || $month = date('m'); 
    $year 
     || $year = date('y'); 
    $timestamp = mktime(0, 0, 0, $month, 1, $year); 
    return date('Y-m-t', $timestamp); 
} 
1

爲了得到月份,利用最後一天:

date('Y-m-t', strtotime("$year-$month-01")) 

't'代表「給定月份中的天數」,即最後一天。不需要添加和減去任何東西。

1

下面將輸出與當年每個月的最後一天選項的選擇框:

echo "<select>";  
for($i=1;$i<=12;$i++){  
    echo "<option>".date('Y-m-t', strtotime(date("Y")."-".$i."-01"))."</option>";  
}  
echo "</select>"; 

如果你想設置爲不同的年份,只需用,比如更換date("Y")"2010" 。例如,您可以循環使用多年,運行代碼爲每個選項輸出選項。

0

我覺得這是你的代碼的問題:

原來的$ increm_date是「2011-06-01」;

在while循環$ increm_date AA某一點爲2011-08-31(八月的最後一天)

在循環添加一個月所以$ increm_date是2011-10-01(的第一天10月,而不是9月的最後),所以你打電話給提供十月十二月的last_day_of_month。

我不確定這一點。要在last_day_of_month之前嘗試打印$ increm_date,請調用