使用现有日期获取每月的最后一天


Get last day of month using existing date

我目前正在使用DateTime对象执行一些涉及日期的计算。在这个例子中,我试图使用预先存在的日期来获取一个月的最后一天。我尝试了以下代码,结果$endDate的值不正确,即1970-1-1

$startDate = new DateTime(date("Y-m-1"));
$endDate = new DateTime(date("Y-m-d", strtotime("last day of month", $startDate->format("Y-m-d"))));
echo "The start date should be 2016-1-1: " . $startDate->format("Y-m-d") . "<br />";
echo "The end date should be 2016-1-31: " . $endDate->format("Y-m-d") . "<br />";

如何使其正确工作,以便$endDate达到所需的结果?我不希望是这个月;它应该适用于我通过$startDate提供的任何日期字符串。

strtotime期望第二个参数是时间戳。试试这个:

$endDate = new DateTime(date("Y-m-d", strtotime("last day of month", $startDate->getTimestamp())));

在日期时间中使用char"t",因为它是给定月份中的天数

$endDate = new DateTime(date("Y-m-t"));

此页面可能有您想要的答案:如何从日期开始查找一个月的最后一天?

应用于您的代码:

$startDate = new DateTime(date("Y-m-1"));
$endDate = new DateTime(date("Y-m-t", $startDate->getTimestamp()));
echo "The start date should be 2016-1-1: " . $startDate->format("Y-m-d") . "<br />";
echo "The end date should be 2016-1-31: " . $endDate->format("Y-m-d") . "<br />";

使用下面的一些建议修复了它。

$startDate = new DateTime(date("2012-4-1"));
$endDate = new DateTime(date("Y-m-t", strtotime($startDate->format("Y-m-d"))));
echo "The start date should be 2012-4-1: " . $startDate->format("Y-m-d") . "<br />";
echo "The end date should be 2012-4-30: " . $endDate->format("Y-m-d") . "<br />";

我已经证实这是有效的。