PHP subtract 1 month from date formatted with date ('m-Y')

后端 未结 10 581
北恋
北恋 2020-12-20 11:11

I\'m trying to subtract 1 month from a date.

$today = date(\'m-Y\');

This gives: 08-2016

How can I subtract a month to get 07

相关标签:
10条回答
  • 2020-12-20 11:45

    Warning! The above-mentioned examples won't work if call them at the end of a month.

    <?php
    $now = mktime(0, 0, 0, 10, 31, 2017);
    echo date("m-Y", $now)."\n";
    echo date("m-Y", strtotime("-1 months", $now))."\n";
    

    will output:

    10-2017
    10-2017
    

    The following example will produce the same result:

    $date = new DateTime('2017-10-31 00:00:00');
    echo $date->format('m-Y')."\n";
    $date->modify('-1 month');
    echo $date->format('m-Y')."\n";
    

    Plenty of ways how to solve the issue can be found in another thread: PHP DateTime::modify adding and subtracting months

    0 讨论(0)
  • 2020-12-20 11:47

    First change the date format m-Y to Y-m

        $date = $_POST('date'); // Post month
        or
        $date = date('m-Y'); // currrent month
    
        $date_txt = date_create_from_format('m-Y', $date);
        $change_format = date_format($date_txt, 'Y-m');
    

    This code minus 1 month to the given date

        $final_date = new DateTime($change_format);
        $final_date->modify('-1 month');
        $output = $final_date->format('m-Y');
    
    0 讨论(0)
  • 2020-12-20 11:47

    I used this to prevent the "last days of month"-error. I just use a second strtotime() to set the date to the first day of the month:

    <?php
    echo $newdate = date("m-Y", strtotime("-1 months", strtotime(date("Y-m")."-01")));
    
    0 讨论(0)
  • 2020-12-20 11:48

    Try this,

    $today = date('m-Y');
    $newdate = date('m-Y', strtotime('-1 months', strtotime($today))); 
    echo $newdate;
    
    0 讨论(0)
提交回复
热议问题