月初和月底的字符串时间不正常


stringtotime beginning and end of the month not working proppely

我有代码:

$month = DateTime::createFromFormat('m/Y', $date);
if ($month) {
    $month = $month -> format('01/m/Y');
}
echo "From ".$startMonth." to ".$endMonth = date("t/m/Y", strtotime($month));

$date是类似"05/2015"的字符串时。

返回:

2015年5月1日至2015年1月31日

但由于某种原因,这个月将成为01,而它应该是05?它为什么要这么做?应该是

2015年5月1日至2015年5日31日

除了在DateTime对象和unix时间戳之间进行不必要的剪切和更改(当您可以使用DateTime对象完成整个操作时……您正在将格式化的日期'01/m/Y'传递给strtotime()……/strtotime()函数指示日期为US日期格式(mm/dd/yy):并且您应该使用'01-m-Y'(带-)作为dd-mm-YYYY如果您想告诉strtotime()这是一个欧洲格式的日期。

有关strtotime() 接受的格式的解释,请参阅PHP文档页面上的"本地化注释"表

然而,使用DateTime对象完成整个操作:

$date = '4/2015';
$month = DateTime::createFromFormat('m/Y', $date);
echo "From " . $month->format('01/m/Y') . " to ". $month->format('t/m/Y');