How to find first day of the next month and remaining days till this date with PHP

前端 未结 15 773
难免孤独
难免孤独 2020-12-08 14:36

How can I find first day of the next month and the remaining days till this day from the present day?

Thank you

相关标签:
15条回答
  • 2020-12-08 14:53

    You could do something like this. To have this functionality, you need to make use of a php library available in https://packagist.org/packages/ishworkh/navigable-date.

    With that is really easy to do what you're asking for here. For e.g:

    $format = 'Y-m-d H:i:s';
    
    $Date = \NavigableDate\NavigableDateFacade::create('2017-02-24');
    var_dump($Date->format($format));
    
    $resetTime = true;
    $resetDays = true;
    
    $NextMonth = $Date->nextMonth($resetTime, $resetDays);
    
    var_dump($NextMonth->format($format));
    
    $DayUntilFirstOfNextMonth = $NextMonth->getDifference($Date);
    
    var_dump('Days left:' . $DayUntilFirstOfNextMonth->format('%d'));
    

    gives you ouput:

    string(19) "2017-02-24 00:00:00"
    string(19) "2017-03-01 00:00:00"
    string(11) "Days left:5"
    

    Note: Additionally this library let you navigate through dates by day(s), week(s), year(s) forward or backward. For more information look into its README.

    0 讨论(0)
  • $firstDayNextMonth = date('Y-m-d', mktime(0, 0, 0, date('m')+1, 1, date('Y')));

    0 讨论(0)
  • 2020-12-08 14:56
    $firstDayNextMonth = date('Y-m-d', strtotime('first day of next month'));
    

    For getting first day after two months from current

    $firstDayAfterTwoMonths = date('Y-m-d', strtotime('first day of +2 month'));
    
    0 讨论(0)
  • 2020-12-08 14:58

    The easiest and quickest way is to use strtotime() which recognizes 'first day next month';

    $firstDayNextMonth = date('Y-m-d', strtotime('first day next month'));
    
    0 讨论(0)
  • 2020-12-08 14:58

    Since I googled this and came to this answer, I figured I'd include a more modern answer that works for PHP 5.3.0+.

    //Your starting date as DateTime
    $currentDate = new DateTime(date('Y-m-d'));
    
    //Add 1 month
    $currentDate->add(new DateInterval('P1M'));
    
    //Get the first day of the next month as string
    $firstDayOfNextMonth = $currentDate->format('Y-m-1');
    
    0 讨论(0)
  • 2020-12-08 14:58
    echo date('Y-m',strtotime("+1 month")).'-01';
    

    Simplest way to achieve this. You can echo or store into variable.

    0 讨论(0)
提交回复
热议问题