You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP自动计算跨月(12日-次月11日)营收问题求助

修正后的PHP特定周期营收统计方案

问题根源

之前的代码存在两个核心问题:

  • 周期结束时间仅设置为次月11日的00:00:00,导致当天所有订单未被统计
  • 手动计算月份天数,无法适配28、30、31天的不同月份

核心解决思路

  • 用PHP DateTime 类自动处理日期逻辑,无需手动计算月份天数
  • 将周期结束时间设为次月11日23:59:59,确保当天所有订单都被纳入统计
  • 直接在SQL中通过 SUM(price * quantity) 计算周期总营收,效率更高

各周期统计代码

1. 当前完整周期(上月12日 → 本月11日)

// 计算周期开始时间:上月12日 00:00:00
$startDate = new DateTime('first day of last month');
$startDate->modify('+11 days')->setTime(0, 0, 0);

// 计算周期结束时间:本月11日 23:59:59
$endDate = new DateTime('first day of this month');
$endDate->modify('+10 days')->setTime(23, 59, 59);

// PDO查询示例
$sql = "SELECT SUM(price * quantity) AS total_revenue 
        FROM orders 
        WHERE created_at BETWEEN :start AND :end";

$stmt = $pdo->prepare($sql);
$stmt->execute([
    ':start' => $startDate->format('Y-m-d H:i:s'),
    ':end' => $endDate->format('Y-m-d H:i:s')
]);

$currentRevenue = $stmt->fetchColumn();
echo "当前周期营收:{$currentRevenue}";

2. 上月完整周期(上上月12日 → 上月11日)

// 计算周期开始时间:上上月12日 00:00:00
$startDate = new DateTime('first day of last month -1 month');
$startDate->modify('+11 days')->setTime(0, 0, 0);

// 计算周期结束时间:上月11日 23:59:59
$endDate = new DateTime('first day of last month');
$endDate->modify('+10 days')->setTime(23, 59, 59);

// PDO查询示例
$sql = "SELECT SUM(price * quantity) AS total_revenue 
        FROM orders 
        WHERE created_at BETWEEN :start AND :end";

$stmt = $pdo->prepare($sql);
$stmt->execute([
    ':start' => $startDate->format('Y-m-d H:i:s'),
    ':end' => $endDate->format('Y-m-d H:i:s')
]);

$lastMonthRevenue = $stmt->fetchColumn();
echo "上月周期营收:{$lastMonthRevenue}";

3. 前三月完整周期(三个月前12日 → 两个月前11日)

// 计算周期开始时间:三个月前12日 00:00:00
$startDate = new DateTime('first day of this month -3 months');
$startDate->modify('+11 days')->setTime(0, 0, 0);

// 计算周期结束时间:两个月前11日 23:59:59
$endDate = new DateTime('first day of this month -2 months');
$endDate->modify('+10 days')->setTime(23, 59, 59);

// PDO查询示例
$sql = "SELECT SUM(price * quantity) AS total_revenue 
        FROM orders 
        WHERE created_at BETWEEN :start AND :end";

$stmt = $pdo->prepare($sql);
$stmt->execute([
    ':start' => $startDate->format('Y-m-d H:i:s'),
    ':end' => $endDate->format('Y-m-d H:i:s')
]);

$threeMonthsAgoRevenue = $stmt->fetchColumn();
echo "前三月周期营收:{$threeMonthsAgoRevenue}";

关键说明

  • 所有周期的结束时间都设置为23:59:59,彻底避免11日订单被遗漏的问题
  • DateTime 类会自动处理28、30、31天的月份差异,无需额外判断
  • 直接在SQL中计算营收总和,比PHP循环处理数据的效率更高

内容的提问来源于stack exchange,提问作者exitmivce

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 23:38:07