如何在PHP中获得每月的最后一天?
考虑到:
$a_date = "2009-11-23"
我想要2009-11-30;鉴于
$a_date = "2009-12-23"
我要2009-12-31。
如何在PHP中获得每月的最后一天?
考虑到:
$a_date = "2009-11-23"
我想要2009-11-30;鉴于
$a_date = "2009-12-23"
我要2009-12-31。
当前回答
我需要下个月的最后一天,也许有人会需要它:
echo date("Y-m-t", strtotime("next month")); //is 2020-08-13, return 2020-09-30
其他回答
试试这个,如果你使用的是PHP 5.3+,
$a_date = "2009-11-23";
$date = new DateTime($a_date);
$date->modify('last day of this month');
echo $date->format('Y-m-d');
为了查找下个月最后的日期,修改如下:
$date->modify('last day of 1 month');
echo $date->format('Y-m-d');
等等。
function first_last_day($string, $first_last, $format) {
$result = strtotime($string);
$year = date('Y',$result);
$month = date('m',$result);
$result = strtotime("{$year}-{$month}-01");
if ($first_last == 'last'){$result = strtotime('-1 second', strtotime('+1 month', $result)); }
if ($format == 'unix'){return $result; }
if ($format == 'standard'){return date('Y-m-d', $result); }
}
http://zkinformer.com/?p=134
如果你知道一个月的最后一天,
public function getLastDateOfMonth($month)
{
$date = date('Y').'-'.$month.'-01'; //make date of month
return date('t', strtotime($date));
}
$this->getLastDateOfMonth(01); //31
$startDate = '2011-12-01';
$endDate = date('Y-m');
while (true) {
try {
$startDateTime = new DateTime($startDate);
$startDateTime->add(new DateInterval('P1M'));
$startDate = $startDateTime->format('Y-m-d');
$endTime = $startDateTime->format('Y-m-t');
echo $startDate . ' => ' . $endTime . PHP_EOL;
if ($startDateTime->format('Y-m') == $endDate) {
break;
}
} catch (Exception $exception) {
var_dump($exception->getMessage());
break;
}
}
在测试了许多解决方案之后,这个方法最适合我。
$date1 = $year.'-'.$month;
$d = date_create_from_format('Y-m',$date1);
$last_day = date_format($d, 't');