首页 > 解决方案 > PHP获取上个月最后一天和下个月第一天

问题描述

如果我有例如:

'2020-01-01'

我想要两个日期:

- 上个月的最后一天:

'2019-12-31'

- 下个月的第一天:

'2020-02-01'

我尝试使用类似的东西,echo date("Y-n-31", strtotime('2020-01-01'));但我不知道。

谢谢你。

标签: phpdatedatetime

解决方案


使用以下代码:

<?php

$month_end = new DateTime("last day of last month");
$month_ini = new DateTime("first day of next month");

echo $month_end->format('Y-m-d'); // will print, Last day of last month
echo $month_ini->format('Y-m-d'); // will print First day of next month

?>

使用具有用户定义日期的 Datetime 对象(自定义日期)

# with datetime object
$d1 = new DateTime('2019-12-01');
$d1 -> modify('last day of last month');
echo $d1 -> format('d.m.Y'), "\n";

$d2 = new DateTime('2019-12-01');
$d2 -> modify('first day of next month');
echo $d2 -> format('d.m.Y'), "\n";

Output:
30.11.2019
01.01.2020

推荐阅读