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

后端 未结 11 919
无人及你
无人及你 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:28

    Just to verify that I didn't miss any loose ends:

    $startDay = 1;
    
    if (date("m") == 1) {
        $startMonth = 12;
        $startYear = date("Y") - 1;
    
        $endMonth = 12;
        $endYear = date("Y") - 1;
    }
    else {
        $startMonth = date("m") - 1;
        $startYear = date("Y");
    
        $endMonth = date("m") - 1;
        $endYear = date("Y");
    }
    
    $endDay = date("d") - 1;
    
    $startDate = date('Y-m-d', mktime(0, 0, 0, $startMonth , $startDay, $startYear));
    $endDate = date('Y-m-d', mktime(0, 0, 0, $endMonth, $endDay, $endYear));
    
    0 讨论(0)
  • 2020-12-01 12:29
    <?php
    echo "Month Start - " . $monthStart = date("Y-m-1") . "<br/>";
    $num = cal_days_in_month(CAL_GREGORIAN, date("m"), date("Y"));
    echo "Monthe End - " . $monthEnd = date("Y-m-".$num);
    ?>
    
    0 讨论(0)
  • 2020-12-01 12:30

    OK, first is dead easy.

    date ('Y-m-d', mktime(0,0,0,MM,01,YYYY));
    

    Last is a little trickier, but not much.

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

    If I remember my PHP date stuff correctly...

    **edit - Gah! Beaten to it about a million times...

    Edit by Pat:

    Last day should have been

    date ('Y-m-d', mktime(0,0,0,$MM + 1,0,$YYYY)); // Day zero instead of -1
    
    0 讨论(0)
  • 2020-12-01 12:37

    First day is always YYYY-MM-01, isn't it? Example: date("Y-M-d", mktime(0, 0, 0, 8, 1, 2008))

    Last day is the previous day of the next month's first day:

    $date = new DateTime("2008-09-01");
    $date->modify("-1 day");
    echo $date->format("Y-m-d");
    
    0 讨论(0)
  • 2020-12-01 12:46

    try this to get the number of days in the month:

    $numdays = date('t', mktime(0, 0, 0, $m, 1, $Y));
    
    0 讨论(0)
提交回复
热议问题