PHP: simplest way to get the date of the month 6 months prior on the first?

前端 未结 4 1737
悲哀的现实
悲哀的现实 2021-01-01 09:09

So if today was April 12, 2010 it should return October 1, 2009

Some possible solutions I\'ve googled seem overly complex, any suggestions?

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-01 09:41

    It was discussed in comments but the accepted answer has some unneeded strtotime() calls. Can be simplified to:

    date("F 1, Y", strtotime("Feb 2, 2010 - 6 months"));
    

    Also, you can use DateTime() like this which I think is equally as readable:

    (new DateTime('Feb 2, 2010'))->modify('-6 months')->format('M 1, Y');
    

    Or using static method....

    DateTime::createFromFormat('M j, Y','Feb 2, 2010')
        ->modify('-6 months')
        ->format('M 1, Y');
    

提交回复
热议问题