php 获取当前月的上一个月
时间: 2023-07-07 22:09:52 浏览: 45
要获取当前月的上一个月,可以使用 PHP 中的 date() 和 strtotime() 函数。具体代码如下:
```php
$lastMonth = date('Y-m', strtotime('-1 month'));
echo $lastMonth;
```
解释一下代码:首先使用 strtotime('-1 month') 获取当前时间的上一个月的时间戳,然后使用 date() 函数将时间戳格式化为 'Y-m' 的字符串,即年份和月份,存储在变量 $lastMonth 中。最后使用 echo 输出 $lastMonth 变量的值即可。
相关问题
PHP 获取当天以及未来一个月的日期
可以使用PHP的日期和时间函数来获取当天以及未来一个月的日期。以下是一个示例代码:
```php
<?php
// 获取当前日期
$current_date = date('Y-m-d');
// 获取未来一个月的日期
$next_month_date = date('Y-m-d', strtotime('+1 month'));
// 输出当前日期和未来一个月的日期
echo '当前日期:' . $current_date . '<br>';
echo '未来一个月的日期:' . $next_month_date;
?>
```
上面的代码中,我们使用了date函数来获取当前日期和未来一个月的日期,其中第一个参数是日期格式字符串,第二个参数是时间戳。在第二个参数中,我们使用strtotime函数来计算未来一个月的日期。
如果要获取未来多个月的日期,可以将第二个参数中的'+1 month'修改为'+2 months'、'+3 months'等。
php 获取上个月的第一天和最后一天
可以使用PHP中的date()和strtotime()函数来获取上个月的第一天和最后一天。具体代码如下:
获取上个月第一天:
```
$first_day_of_last_month = date('Y-m-01', strtotime('-1 month'));
```
获取上个月最后一天:
```
$last_day_of_last_month = date('Y-m-t', strtotime('-1 month'));
```
其中,date()函数用于格式化日期,strtotime()函数用于将字符串转换为时间戳。在第二个例子中,t表示当前月份的天数,因此可以用来获取上个月的最后一天。