PHP 获取上个月第一天216


在 PHP 中,我们可以使用 `date` 函数和 `strtotime` 函数来获取上个月的第一天。

使用 `date` 函数

我们可以使用 `date` 函数来获取当前日期,然后使用 `strtotime` 函数来修改日期。例如:```php
$date = date('Y-m-d');
$lastMonthFirstDay = date('Y-m-01', strtotime('-1 month', strtotime($date)));
```
在这个示例中,`date('Y-m-d')` 获取当前日期,`strtotime('-1 month', strtotime($date))` 将当前日期减去一个月,然后 `date('Y-m-01', $timestamp)` 从修改后的时间戳中获取上个月的第一天。

使用 `DateTime` 类

我们还可以使用 `DateTime` 类来获取上个月的第一天。例如:```php
$date = new DateTime();
$date->modify('-1 month');
$lastMonthFirstDay = $date->format('Y-m-01');
```
在这个示例中,我们创建了一个 `DateTime` 对象,然后使用 `modify` 方法将日期减去一个月。最后,使用 `format` 方法获取上个月的第一天。

示例输出

以下输出显示了如何使用上面两种方法获取上个月的第一天:```php
echo "使用 date() 函数:" . date('Y-m-01', strtotime('-1 month', strtotime(date('Y-m-d')))) . "";
echo "使用 DateTime 类:" . (new DateTime())->modify('-1 month')->format('Y-m-01') . "";
```
输出:
```
使用 date() 函数:2023-06-01
使用 DateTime 类:2023-06-01
```

2024-11-09


上一篇:PHP 删除二维数组元素的全面指南

下一篇:HTTP 头部和 PHP 文件过期的处理