这些答案并不是我想要的:
在php中获取上个月'如何从日期开始查找一个月的最后一天?
我有下面的代码,用于打印一个选择框,其中包含给定日期的所有最后一天的日期:
$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);
}
我从这里借的
奇怪的是,我得到了这些日期:
2011-07-31
2011-08-31
2011-10-31
但没有2011-09-30
!这可能与9月只有30天有关,对吧?
有人能发现问题吗?我已经盯着它好长时间了....
可以直接使用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);
}
要获取月份的最后一天,使用:
date('Y-m-t', strtotime("$year-$month-01"))
't'
表示"该月的天数",即最后一天。不需要加减任何东西
下面的命令将输出一个选择框,其中包含当前年份中每个月的最后一天的选项:
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"
。例如,您可以循环若干年,运行代码以输出每一年的选项。
我认为这是你那段代码的问题:
原$increm_date为"2011-06-01";
$increm_date是2011-08-31(八月的最后一天)在您添加一个月的周期中,因此$increm_date是2011-10-01(10月的第一天,而不是9月的最后一天),因此您调用last_day_of_month提供10月而不是9月。
我不确定这一点。要进行测试,请在last_day_of_month