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

21 篇文章 0 订阅

发生场景

在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))) . "<br />";
        }
    }

 

原因(官网) 

# 官网文档:PHP: strtotime - Manual

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

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

解决(官网) 

# 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))) . "<br />";
        }
}

 感谢阅读,欢迎讨论

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

东小记

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值