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

前端 未结 4 1738
悲哀的现实
悲哀的现实 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');
    
    0 讨论(0)
  • 2021-01-01 09:53

    A bit hackish but works:

    <?php
    
    $date = new DateTime("-6 months");
    $date->modify("-" . ($date->format('j')-1) . " days");
    echo $date->format('j, F Y');
    
    ?>
    
    0 讨论(0)
  • 2021-01-01 09:57

    use a combination of mktime and date:

    $date_half_a_year_ago = mktime(0, 0, 0, date('n')-6, 1, date('y'))
    

    to make the new date relative to a given date and not today, call date with a second parameter

    $given_timestamp = getSomeDate();
    $date_half_a_year_ago = mktime(0, 0, 0, date('n', $given_timestamp)-6, 1, date('y', $given_timestamp))
    

    to output it formatted, simply use date again:

    echo date('F j, Y', $date_half_a_year_ago);
    
    0 讨论(0)
  • 2021-01-01 10:00

    Hm, maybe something like this;

    echo date("F 1, Y", strtotime("-6 months"));
    

    EDIT;

    if you would like to specify a custom date use;

    echo date("F, 1 Y", strtotime("-6 months", strtotime("Feb 2, 2010")));
    
    0 讨论(0)
提交回复
热议问题