我目前正在使用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
提供的任何日期字符串。
答案 0 :(得分:0)
strtotime
期望第二个参数是时间戳。试试这个:
$endDate = new DateTime(date("Y-m-d", strtotime("last day of month", $startDate->getTimestamp())));
答案 1 :(得分:0)
使用char&#34; t&#34;在您的日期时间,因为它是给定月份的天数
$endDate = new DateTime(date("Y-m-t"));
答案 2 :(得分:0)
此页面可能有您寻求的答案: How to find the last day of the month from date?
应用于您的代码:
(newNode: Node, offset: number): void
答案 3 :(得分:0)
使用以下一些建议修正了它。
$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 />";
我已经确认这是有效的。