Add six months in php

后端 未结 4 812
难免孤独
难免孤独 2020-12-03 21:46

I\'m trying to get the month, six months out from the current date.

I\'ve tried using:

date(\'d\', strtotime(\'+6 month\', time()));

B

相关标签:
4条回答
  • 2020-12-03 22:28

    You don't need to pass time() to strtotime, as it is the default.

    Apart from that, your approach is correct - except that you take date('d') (which is putting out the day) and not date('m') for the month, so echo date('m', strtotime('+6 month')); should do.

    Nevertheless, I would recommend using the DateTime way, which John stated. DateTime has several advantages over the "old" date functions, for example they don't stop working when the seconds since the UNIX big bang don't fit into an 32bit integer any more.

    0 讨论(0)
  • 2020-12-03 22:33

    If you still wanted to use strtotime and the date function as opposed to a DateTime() object, the following would work:

    date('d', strtotime('+6 months'));
    
    0 讨论(0)
  • 2020-12-03 22:37

    You can use the DateTime class in conjunction with the DateInterval class:

    <?php
    $date = new DateTime();
    $date->add(new DateInterval('P6M'));
    
    echo $date->format('d M Y');
    
    0 讨论(0)
  • 2020-12-03 22:45

    I find working with DateTime much easier to use:

    $datetime = new \DateTime();
    $datetime->modify('+6 months');
    echo $datetime->format('d');
    

    or

    $datetime = new \DateTime();
    $datetime->add(new DateInterval('P6M'));
    echo $datetime->format('d');
    

    or in PHP version 5.4+

    echo (new \DateTime())->add(new \DateInterval('P6M'))->format('d');
    
    0 讨论(0)
提交回复
热议问题