bart2puck
bart2puck

Reputation: 2522

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?

Upvotes: 2

Views: 1478

Answers (4)

user3892260
user3892260

Reputation: 1035

// previous month
echo date("F t, Y", strtotime("last month"));

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

Upvotes: 0

Ave
Ave

Reputation: 4430

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";
?>

Upvotes: 4

Anupriya Malaiya
Anupriya Malaiya

Reputation: 11

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'

Upvotes: 0

Azeez Kallayi
Azeez Kallayi

Reputation: 2642

Can you please try previous month instead of last month

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

Upvotes: 0

Related Questions