PHP Strtotime -1month -2month

前端 未结 6 597
感情败类
感情败类 2020-12-06 06:00

This was working fine yesterday with no changes to the code.

echo date(\"M\", strtotime(\"-3 month\", time()) );
echo date(\"M\", strtotime(\"-2 month\", tim         


        
6条回答
  •  星月不相逢
    2020-12-06 06:24

    Gorden correctly identified the issue, but I wanted to give another solution that was helpful and not as technical. Just use "first day of" or "last day of" in your strtotime. Ex, these following examples overcome the issue on a 31st of a month:

    // Today is May 31st
    //All the following return 2012-04-30
    echo date('Y-m-d', strtotime("last day of -1 month"));
    echo date('Y-m-d', strtotime("last day of last month"));
    echo date_create("last day of -1 month")->format('Y-m-d'); 
    
    // All the following return 2012-04-01
    echo date('Y-m-d', strtotime("first day of -1 month")); 
    echo date('Y-m-d', strtotime("first day of last month"));
    echo date_create("first day of -1 month")->format('Y-m-d');
    

提交回复
热议问题