繁体   English   中英

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

[英]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 />";

我已经证实这可行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM