February and strtotime

2019-08-07 14:23发布

问题:

okay?

I'm trying to hit a calculation date here, however I am not getting ..

What happens is the following:

$AtualMenos3 = date("m-d-Y", strtotime("2013-03-31 -3 month"));
$AtualMenos2 = date("m-d-Y", strtotime("2013-03-31 -2 month"));
$AtualMenos1 = date("m-d-Y", strtotime("2013-03-31 -1 month"));
$AtualMes = date("m-d-Y", strtotime("2013-03-31"));

The correct should be:

03-31-2013
02-28-2013
01-31-2013
12-31-2012

However, this php calculating the date wrong, because when month is February (which only has 28 days) the calculation goes wrong ..

Real output:

03-31-2013
03-03-2013
01-31-2013
12-31-2012

Does anyone know give me a light on how I fix this? because this complicated .. I'm out of ideas ... I can not think of anything: \

回答1:

    $datetime = new DateTime('2013-03-31');
    $datetime->modify('-1 month');
    echo $datetime->format('Y-m-t') . "<br>";
    $datetime->modify('-1 month');
    echo $datetime->format('Y-m-t') . "<br>";
    $datetime->modify('-1 month');
    echo $datetime->format('Y-m-t') . "<br>";

See it in action



回答2:

A workaround to find the last day of the month would be:

 $lastDay = date("m-d-Y",(strtotime('next month',strtotime(date("m-01-Y"))) - 1)); 

Hope it will help.



回答3:

If you want to stick with strtotime(), you can easily calculate the last day of a month by subtracting one day from the next month.

echo date("m-d-Y", strtotime("Apr 2013 -1 day")); // yields 03-31-2013
echo date("m-d-Y", strtotime("Mar 2013 -1 day")); // yields 02-28-2013
echo date("m-d-Y", strtotime("Feb 2013 -1 day")); // yields 01-31-2013