如何在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。
当前回答
您可以在日期函数中使用“t”来获得特定月份中的天数。
代码是这样的:
function lastDateOfMonth($Month, $Year=-1) {
if ($Year < 0) $Year = 0+date("Y");
$aMonth = mktime(0, 0, 0, $Month, 1, $Year);
$NumOfDay = 0+date("t", $aMonth);
$LastDayOfMonth = mktime(0, 0, 0, $Month, $NumOfDay, $Year);
return $LastDayOfMonth;
}
for($Month = 1; $Month <= 12; $Month++)
echo date("Y-n-j", lastDateOfMonth($Month))."\n";
代码是自解释的。希望这能有所帮助。
其他回答
使用Zend_Date非常简单:
$date->setDay($date->get(Zend_Date::MONTH_DAYS));
这是一个更优雅的表达月底的方式:
$thedate = Date('m/d/Y');
$lastDayOfMOnth = date('d', mktime(0,0,0, date('m', strtotime($thedate))+1, 0, date('Y', strtotime($thedate))));
您可以在日期函数中使用“t”来获得特定月份中的天数。
代码是这样的:
function lastDateOfMonth($Month, $Year=-1) {
if ($Year < 0) $Year = 0+date("Y");
$aMonth = mktime(0, 0, 0, $Month, 1, $Year);
$NumOfDay = 0+date("t", $aMonth);
$LastDayOfMonth = mktime(0, 0, 0, $Month, $NumOfDay, $Year);
return $LastDayOfMonth;
}
for($Month = 1; $Month <= 12; $Month++)
echo date("Y-n-j", lastDateOfMonth($Month))."\n";
代码是自解释的。希望这能有所帮助。
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
另一种使用mktime而不是date('t')的方法:
$dateStart= date("Y-m-d", mktime(0, 0, 0, 10, 1, 2016)); //2016-10-01
$dateEnd = date("Y-m-d", mktime(0, 0, 0, 11, 0, 2016)); //This will return the last day of october, 2016-10-31 :)
所以用这种方法,它会计算它是31 30还是29