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

PHP如何基于指定日期获取本季度及上季度起止Unix时间戳

PHP季度起止时间戳计算实现方案

PHP原生的DateTime系列类就可以满足需求,不需要引入第三方库,能完美解决时区、跨年边界问题,完整实现如下:

实现代码

/**
 * 计算指定日期对应季度的4个时间戳
 * @param string|int $inputDate 支持日期字符串或Unix时间戳
 * @param string $timezone 时区,默认取系统配置时区
 * @return array
 * @throws Exception
 */
function getQuarterTimestamps($inputDate, string $timezone = null): array
{
    $timezone = $timezone ?? date_default_timezone_get();
    $tz = new DateTimeZone($timezone);
    
    // 解析输入日期
    if (is_int($inputDate)) {
        $dt = (new DateTime())->setTimestamp($inputDate)->setTimezone($tz);
    } else {
        $dt = new DateTime($inputDate, $tz);
    }

    $year = (int)$dt->format('Y');
    $month = (int)$dt->format('n');
    $currentQuarter = (int)ceil($month / 3);
    $currentQuarterFirstMonth = ($currentQuarter - 1) * 3 + 1;

    // 1. 本季度第一秒
    $currentQFirst = (new DateTime())->setTimezone($tz)
        ->setDate($year, $currentQuarterFirstMonth, 1)
        ->setTime(0, 0, 0)
        ->getTimestamp();

    // 2. 本季度最后一秒
    $currentQLast = (new DateTime())->setTimezone($tz)
        ->setDate($year, $currentQuarterFirstMonth + 3, 1)
        ->modify('-1 day')
        ->setTime(23, 59, 59)
        ->getTimestamp();

    // 3. 上季度第一秒
    $prevQFirst = (new DateTime())->setTimezone($tz)
        ->setDate($year, $currentQuarterFirstMonth, 1)
        ->modify('-3 month')
        ->setTime(0, 0, 0)
        ->getTimestamp();

    // 4. 上季度最后一秒
    $prevQLast = (new DateTime())->setTimezone($tz)
        ->setDate($year, $currentQuarterFirstMonth, 1)
        ->modify('-1 second')
        ->getTimestamp();

    return [
        'current_quarter_first' => $currentQFirst,
        'current_quarter_last' => $currentQLast,
        'previous_quarter_first' => $prevQFirst,
        'previous_quarter_last' => $prevQLast
    ];
}

// 使用示例
date_default_timezone_set('Asia/Shanghai');
// 测试跨年场景:输入2024年1月5日
$result = getQuarterTimestamps('2024-01-05');
// 格式化输出验证结果
print_r(array_map(function($ts) {
    return date('Y-m-d H:i:s', $ts);
}, $result));

核心说明

  • 时区处理:代码默认读取PHP配置的默认时区,也可以手动传入时区参数(比如Asia/Shanghai),所有时间计算都基于指定时区,不会出现时区偏移导致的时间错误
  • 跨年兼容:上季度计算直接通过modify方法做时间偏移,PHP原生会自动处理年份切换、大小月、闰月等场景,不需要手动编写边界判断逻辑
  • 输入兼容:支持传入任意合法日期字符串,也支持直接传入Unix时间戳作为计算基准

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 18:27:02