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

后端 未结 11 938
无人及你
无人及你 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: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'));

提交回复
热议问题