Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Last day of previous months calculating wrong

Tags:

date

php

I'm having issues calculating the last day of the previous 12 months.

Here's the code I'm using:

    for ($i = 0; $i <= 12; $i++) {
        $start[] = date("Y-m-01", strtotime( date( 'Y-m-01' )." -$i months"));
        $end[] = date( 'Y-m-t', strtotime($start[$i]. -1*$i .' month') );

        echo $start[$i] . " - " . $end[$i] . "<br/>";
    }

This produces:

2015-10-01 – 2015-10-31
2015-09-01 – 2015-08-31
2015-08-01 – 2015-06-30
2015-07-01 – 2015-04-30
2015-06-01 – 2015-02-28
2015-05-01 – 2014-12-31
2015-04-01 – 2014-10-31
2015-03-01 – 2014-08-31
2015-02-01 – 2014-06-30
2015-01-01 – 2014-04-30
2014-12-01 – 2014-02-28
2014-11-01 – 2013-12-31
2014-10-01 – 2013-10-31

Notice that the last day for September is not correct (it's showing August 31st as the last day). This happens for multiple months.

Any ideas?

like image 742
Nicholas Avatar asked Oct 27 '15 03:10

Nicholas


2 Answers

What is the desired result? I assume you're just trying to display the first and last days of the month? Your code iterates over $i. So every time it iterates, it's removing 0 months, 1 month, 2, 3, 4, 5... etc.

Just remove that code completely. Y-m-t will do.

for ( $i = 0; $i <= 12; $i++ ) {
    $start[] = date('Y-m-01', strtotime( date( 'Y-m-01' )." -$i months"));
    $end[]   = date('Y-m-t',  strtotime( $start[$i] ) );

    echo $start[$i] . " - " . $end[$i] . "<br/>";
}

Results in

2015-10-01 - 2015-10-31
2015-09-01 - 2015-09-30
2015-08-01 - 2015-08-31
2015-07-01 - 2015-07-31
2015-06-01 - 2015-06-30
2015-05-01 - 2015-05-31
2015-04-01 - 2015-04-30
2015-03-01 - 2015-03-31
2015-02-01 - 2015-02-28
2015-01-01 - 2015-01-31
2014-12-01 - 2014-12-31
2014-11-01 - 2014-11-30
2014-10-01 - 2014-10-31
like image 146
Christian Avatar answered Oct 04 '22 02:10

Christian


I assume it's because of your iteration while setting $end[]. This, however seems to work:

for ($i = 0; $i <= 12; $i++) {
    $start[] = date("Y-m-01", strtotime( date( 'Y-m-01' )." - $i months"));
    $end[] = date("Y-m-t",strtotime("last day of " . date("Y-m", strtotime($start[$i]))));

    echo $start[$i] . " - " . $end[$i] . "\n";
}

Or as @Christian Varga answered:

$end[]   = date('Y-m-t',  strtotime( $start[$i] ) );

Which returns:

2015-10-01 - 2015-10-31
2015-09-01 - 2015-09-30
2015-08-01 - 2015-08-31
2015-07-01 - 2015-07-31
2015-06-01 - 2015-06-30
2015-05-01 - 2015-05-31
2015-04-01 - 2015-04-30
2015-03-01 - 2015-03-31
2015-02-01 - 2015-02-28
2015-01-01 - 2015-01-31
2014-12-01 - 2014-12-31
2014-11-01 - 2014-11-30
2014-10-01 - 2014-10-31

Example/Demo

like image 37
Darren Avatar answered Oct 04 '22 03:10

Darren