In PHP, is there an easy way to get the first and last date of a month?

后端 未结 11 918
无人及你
无人及你 2020-12-01 11:47

I need to get the first and last day of a month in the format YYYY-MM-DD given only the month and year. Is there a good, easy way to do this?

相关标签:
11条回答
  • 2020-12-01 12:19

    The easiest way to do this with PHP is

    $dateBegin = strtotime("first day of last month");  
    $dateEnd = strtotime("last day of last month");
    
    echo date("MYDATEFORMAT", $dateBegin);  
    echo "<br>";        
    echo date("MYDATEFORMAT", $dateEnd);
    

    Or the last week

    if (date('N', time()) == 7) {
    $dateBegin = strtotime("-2 weeks Monday");
    $dateEnd = strtotime("last Sunday");
    } else {
    $dateBegin = strtotime("Monday last week"); 
    $dateEnd = strtotime("Sunday last week");   
    }
    

    Or the last year

    $dateBegin = strtotime("1/1 last year");
    $dateEnd = strtotime("12/31 this year");
    
    0 讨论(0)
  • 2020-12-01 12:22
    $first = date('Y-m-d', mktime(0, 0, 0, $month, 1, $year));
    $last = date('Y-m-t', mktime(0, 0, 0, $month, 1, $year));
    

    See date() in PHP documentation.

    0 讨论(0)
  • 2020-12-01 12:23

    From here(get next month last day) that is marked as duplicated, so i can't add comment there, but people can got bad answers from there.

    Correct one for last day of next month:

    echo ((new DateTime(date('Y-m').'-01'))->modify('+1 month')->format('Y-m-t'));
    

    Correct one for first day of next month:

    echo ((new DateTime(date('Y-m').'-01'))->modify('+1 month')->format('Y-m-01'));
    

    Code like this will be providing March from January, so that's not what could be expected.

    echo ((new DateTime())->modify('+1 month')->format('Y-m-t'));

    0 讨论(0)
  • 2020-12-01 12:26

    Example; I want to get first day and last day of current month.

    $month   = (int) date('F');
    $year    = (int) date('Y');
    
    date('Y-m-d', mktime(0, 0, 0, $month + 1, 1, $year)); //first
    date('Y-m-d', mktime(0, 0, 0, $month + 2, 0, $year)); //last
    

    When you run this for instance at date 2015-01-09, the first and last values will be sequentially;

    2015-01-01
    2015-01-31
    

    Tested.

    0 讨论(0)
  • 2020-12-01 12:27

    By the way @ZombieSheep solution

    date ('Y-m-d', mktime(0,0,0,$MM + 1,-1,$YYYY));
    

    does not work it should be

    date ('Y-m-d', mktime(0,0,0,$MM + 1,0,$YYYY)); // Day zero instead of -1
    

    Of course @Michał Słaby's accepted solution is the simplest.

    0 讨论(0)
  • 2020-12-01 12:28

    The first day of the month is always 1. So it will become

    YYYY-MM-01
    

    the last day can be calculated as:

    <?php
        $num = cal_days_in_month(CAL_GREGORIAN, 8, 2003); // 31
        echo "There was $num days in August 2003";
    ?>
    
    0 讨论(0)
提交回复
热议问题