【PHP】简记问题:使用strtotime(‘-1 month‘, time)获取上个月第一天时间戳出错

发生场景

在7月31号是查看统计上个月订单购买总金额,查询结果为0

$preMonthStart = strtotime(date('Ym01', strtotime("-1 month")));
$curMonthStart = strtotime(date('Ym01'));
# 统计上月份实际订单金额
$sql = "SELECT count(money) FROM orders WHERE confirm_time > {$preMonthStart} AND confirm_time < {$curMonthStart}"

问题排查

操作说明:读取2023年整年每一天对应的上月月初的日期,比对日期

public function get_order_lastmomth_money()
    {
        $day = strtotime("January 1, 2023");
        for ($i = 0;$i < 365;$i++) {
            echo "当前日期:".date("Ymd",$day + ($i * 86400)) . "-上月月初日期:" . date("Ym01", strtotime("-1 Month", $day + ($i * 86400))) . "
"; } }

【PHP】简记问题:使用strtotime(‘-1 month‘, time)获取上个月第一天时间戳出错_第1张图片

 

原因(官网) 

# 官网文档:PHP: strtotime - Manual

strtotime("-1 month",time());

以当前时间戳的日数据在上个月找到对应的日数据,即(3月01日找2月01日,因此3月29号在2月份找不到29号,直接往后+1天,即3月01号

【PHP】简记问题:使用strtotime(‘-1 month‘, time)获取上个月第一天时间戳出错_第2张图片

解决(官网) 

# first day of last month 上个月的第一天
# strtotime(date('Ymd')) 当天的时间戳
date('Ymd',strtotime("first day of last month", strtotime(date('Ymd'))))

public function get_order_lastmomth_money(){
        $day = strtotime("January 1, 2023");
        for ($i = 0;$i < 365;$i++) {
            echo "当前日期:".date("Ymd",$day + ($i * 86400)) . "-上月月初日期:" . date("Ymd", strtotime("first day of last month", $day + ($i * 86400))) . "
"; } }

 感谢阅读,欢迎讨论

你可能感兴趣的:(PHP,后端,php,后端)