将日期格式化为该月的第一天/最后一天


Format date as the first/last day of the month

我有"Y-m"格式的日期字符串。日在这里无关紧要。现在我需要从这些日期字符串创建另一个日期,wheere day应该是该月的第一天或最后一天。我试过这段代码:

$curDate = DateTime::createFromFormat('Y-m', $datestring1);
$dt =  $curDate->format('Y-m-d');

这里的问题是它使用月份的当前日期创建日期。我怎样才能强迫它在第一天或最后一天这样做?

谢谢

第一天:

$dt = $curDate->format('Y-m-01');

最后一天:

$dt = $curDate->format('Y-m-t');

t:给定月份的天数

http://php.net/manual/en/function.date.php

您可以指定硬代码值

$curDate = DateTime::createFromFormat('Y-m', $datestring1);
$dt =  $curDate->format('Y-m-1'); //if you want first day
$dt =  $curDate->format('Y-m-t'); //if you want last day