我需要使用php找到未来的日期。但使用php,我无法获得正确的二月日期。我在下面发布了我的代码。我需要二月的结束日期。提前感谢。
<?php
$date = '2011-12-31';
$dateOneMonthAdded = strtotime(date("Y-m-d", strtotime($date)) . " +2 month");
$end_date=date("Y-m-d",$dateOneMonthAdded);
echo date("Y-m-d",strtotime(date("Y-m-d", strtotime($end_date))));
?>
您可以使用3月1日减去1天:
$date = date_create('2012-03-01');
$date->modify("-1 day");
echo $date->format("Y-m-d");
试试这个代码。
<?php
$date = '2011-12-31';
$dateOneMonthAdded = strtotime(date("Y-m-t", strtotime($date)) . " +2 month");
$end_date=date("Y-m-t",$dateOneMonthAdded);
echo date("Y-m-d",strtotime(date("Y-m-d", strtotime($end_date))));
?>
如果你绝对需要使用strtotime,你可以试试这个:
<?php
$date = '2011-12-31';
$dateOneMonthAdded = strtotime(date("Y-m-d", strtotime($date)) . ", next month, last day of next month");
$end_date=date("Y-m-d",$dateOneMonthAdded);
echo date("Y-m-d",strtotime(date("Y-m-d", strtotime($end_date))));
?>
这将回报您的期望:2012-02-29。
您也可以在PHP手册中查看strtotime的相对格式。
$dt = new DateTime();
$dt->setDate(2011, 12, 31);
$dt->modify('last day of +2 month');
//or
$dt->modify('+2 month -2 day');
//or
$dt->modify('next month last day of next month');
print_r ($dt);
使用以下代码查找给定月份的第一天/最后一天,
<?php
function findFirstAndLastDay($anyDate)
{
//$anyDate = '2009-08-25'; // date format should be yyyy-mm-dd
list($yr,$mn,$dt) = split('-',$anyDate); // separate year, month and date
$timeStamp = mktime(0,0,0,$mn,1,$yr); //Create time stamp of the first day from the give date.
$firstDay = date('D',$timeStamp); //get first day of the given month
list($y,$m,$t) = split('-',date('Y-m-t',$timeStamp)); //Find the last date of the month and separating it
$lastDayTimeStamp = mktime(0,0,0,$m,$t,$y);//create time stamp of the last date of the give month
$lastDay = date('D',$lastDayTimeStamp);// Find last day of the month
$arrDay = array("$firstDay","$lastDay"); // return the result in an array format.
return $arrDay;
}
//Usage
$dayArray=array();
$dayArray=findFirstAndLastDay('2009-02-25');
print $dayArray[0];
print $dayArray[1];
?>
<?php
$date = '2011-12-31';
$tmp_date = strtotime(date("Y-m-1", strtotime($date)) . " +2 month");
$end_date=date("Y-m-t",$tmp_date);
echo date("Y-m-d",strtotime(date("Y-m-d", strtotime($end_date))));
?>
如果您使用的是PHP>=5.2,我强烈建议您使用新的DateTime对象。例如:
$date = '2011-12-31';
$end_date = new DateTime($date);
$end_date->modify('last day of +2 month');
echo $end_date->format('Y-m-d');
实时演示
或
使用strtotime()
$date = '2011-12-31';
$dateOneMonthAdded = strtotime(date("Y-m-d", strtotime($date)) . ", last day of +2 month");
echo $end_date = date("Y-m-d",$dateOneMonthAdded);