PHP获取当前月与上个月时间戳方法
本示例展示了如何在 PHP 中计算当前月份以及上一个月的起始和结束时间戳。内容供开发者参考使用。
当前月份的处理逻辑
<?php
$thismonth = date('m');
$thisyear = date('Y');
$startDay = $thisyear . '-' . $thismonth . '-1';
$endDay = $thisyear . '-' . $thismonth . '-' . date('t', strtotime($startDay));
$b_time = strtotime($startDay);//当前月的月初时间戳
$e_time = strtotime($endDay);//当前月的月末时间戳
上一月份的处理逻辑
<?php
$thismonth = date('m');
$thisyear = date('Y');
if ($thismonth == 1) {
$lastmonth = 12;
$lastyear = $thisyear - 1;
} else {
$lastmonth = $thismonth - 1;
$lastyear = $thisyear;
}
$lastStartDay = $lastyear . '-' . $lastmonth . '-1';
$lastEndDay = $lastyear . '-' . $lastmonth . '-' . date('t', strtotime($lastStartDay));
$b_time = strtotime($lastStartDay);//上个月的月初时间戳
$e_time = strtotime($lastEndDay);//上个月的月末时间戳
核心在于 date 函数中的 t 参数,它用于获取当前月份包含的天数,可能是 28、29、30 或 31 天。该数值即为当月的最后一天是几号。
注:本站还提供了一款 Unix 时间戳转换工具,涵盖多种常见编程语言的时间戳操作方法,可供参考。
Unix 时间戳 (timestamp) 转换工具: 点击使用
希望上述内容对 PHP 程序设计有所帮助。