简体   繁体   中英

php strtotime last day last month function produces 2 months ago

According to server:

 $ date
 Wed Mar  1 01:46:06 EST 2017

php.ini

 date.timezone = America/New_York

When I do this I get an odd result:

 $month = date('M',strtotime('last day last month'));
 $sel = "SELECT records where month='".$month."'";
 echo $sel;

The result is:

  SELECT records where month='Jan';

any ideas why not Feb?

When using "next month", "last month", "+1 month", "-1 month" or any combination of +/-X months.

It will give non-intuitive results on Jan 30th and 31st.

As described at : http://derickrethans.nl/obtaining-the-next-month-in-php.html

<?php
    $d = new DateTime( '2010-01-31' );
    $d->modify( 'next month' );
    echo $d->format( 'F' ), "\n";
?>

In the above, using "next month" on January 31 will output "March" even though you might want it to output "February".

("+1 month" will give the same result. "last month", "-1 month" are similarly affected, but the results would be seen at beginning of March.)

The way to get what people would generally be looking for when they say "next month" even on Jan 30 and Jan 31 is to use "first day of next month":

<?php
    $d = new DateTime( '2010-01-08' );
    $d->modify( 'first day of next month' );
    echo $d->format( 'F' ), "\n";
?>


<?php
    $d = new DateTime( '2010-01-08' );
    $d->modify( 'first day of +1 month' );
    echo $d->format( 'F' ), "\n";
?>

您能不能尝试上个月而不是上个月

  $month = date('M',strtotime('last day of previous month')); 

use code if you want last month

$month = date('M',strtotime('last month'));

$sel = "SELECT records where month='".$month."'";

echo $sel;

Result :

SELECT records where month='Feb'
// previous month
echo date("F t, Y", strtotime("last month"));

// two months ago
echo date("F t, Y", strtotime("last month -1 month"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM