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

后端 未结 11 953
无人及你
无人及你 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 "
    "; 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");
    

提交回复
热议问题