2011-10-04 54 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,请调用