Bryce Matheson
Bryce Matheson

Reputation: 11

Weird php date strtotime issue

I'm seeing a strange issue using the "date" function and "strtotime" in PHP.

echo date('m/d/Y h:i:s a', time())."<br>";       //returns 04/29/2021 12:26:30 pm
echo date('M Y', strtotime('-5 months'))."<br>"; //returns Nov 2020
echo date('M Y', strtotime('-4 months'))."<br>"; //returns Dec 2020
echo date('M Y', strtotime('-3 months'))."<br>"; //returns Jan 2021
echo date('M Y', strtotime('-2 months'))."<br>"; //returns Mar 2021
echo date('M Y', strtotime('-1 months'))."<br>"; //returns Mar 2021
echo date('M Y')."<br>";                         //returns Apr 2021

My server time is correct, as indicated by the first line, but why does strtotime('-2 months') and strtotime('-1 months') return the same value (Mar 2021) twice?

Thanks in advance

Upvotes: 0

Views: 86

Answers (3)

Artier
Artier

Reputation: 1673

its quite simple

echo date('m/d/Y h:i:s a', time())."<br>";     //returns 04/29/2021 12:26:30 pm
echo date('M Y', strtotime('first day of -5 months'))."<br>"; //returns Nov 2020
echo date('M Y', strtotime('first day of -4 months'))."<br>"; //returns Dec 2020
echo date('M Y', strtotime('first day of -3 months'))."<br>"; //returns Jan 2021
echo date('M Y', strtotime('first day of -2 months'))."<br>"; //returns Feb 2021
echo date('M Y', strtotime('first day of -1 months'))."<br>"; //returns Mar 2021
echo date('M Y')."<br>";  

Upvotes: 0

Kinglish
Kinglish

Reputation: 23654

You're testing this function on April 29 echo date('M Y', strtotime('-2 months')). It will return Feb 29, 2021 - a date that doesn't exist, so it's defaulting to the last day of Feb (28) and adding 1 to get March 1.

... I had a solution here but it's a bit of a hack compared to your solution below, so I removed it in favor of yours

Upvotes: 4

Bryce Matheson
Bryce Matheson

Reputation: 11

This resolved it for me:

    echo date("M Y", strtotime("-5 month", strtotime(date("F") . "1"))) . "<br>";
    echo date("M Y", strtotime("-4 month", strtotime(date("F") . "1"))) . "<br>";
    echo date("M Y", strtotime("-3 month", strtotime(date("F") . "1"))) . "<br>";
    echo date("M Y", strtotime("-2 month", strtotime(date("F") . "1"))) . "<br>";
    echo date("M Y", strtotime("-1 month", strtotime(date("F") . "1"))) . "<br>";
    echo date("M Y", time()) . "<br>";

Thank you for the help!

Upvotes: 0

Related Questions