📞 09318539889 📧 yxp@gansuwangzhan.cn

根据指定时间计算指定时间前一个月的开始和结束时间

作者:杨锦龙时间:2025-10-16点击量:0次
/**
 * 计算指定时间的上个月的开始和结束时间(不使用 DateTime)
 *
 * @param string $date 指定的日期时间,格式如 'Y-m-d' 或 'Y-m-d H:i:s',默认为当前时间
 * @param string $format 返回时间的格式,默认为 'Y-m-d H:i:s'
 * @return array 包含上个月开始时间和结束时间的数组
 */
public function getPreviousMonthRange($date = 'now', $format = 'Y-m-d H:i:s') {
    // 将输入日期转换为时间戳
    $timestamp = is_string($date) ? strtotime($date) : (is_int($date) ? $date : time());
    if ($timestamp === false) {
        $timestamp = time(); // 如果解析失败,使用当前时间
    }
    // 获取当前月的第一天的时间戳
    $firstDayThisMonth = strtotime(date('Y-m-01 00:00:00', $timestamp));
    // 获取上个月第一天的时间戳
    $firstDayLastMonth = strtotime('-1 month', $firstDayThisMonth);
    // 上个月的开始时间:上个月第一天 00:00:00
    $startOfPreviousMonth = $firstDayLastMonth;
    // 上个月的结束时间:上个月最后一天 23:59:59
    // 先获取上个月最后一天的日期,然后设置时间为 23:59:59
    $lastDayLastMonth = strtotime('last day of previous month', $timestamp);
    $endOfPreviousMonth = strtotime(date('Y-m-d', $lastDayLastMonth) . ' 23:59:59');
    return [
        'start' => date($format, $startOfPreviousMonth),
        'end' => date($format, $endOfPreviousMonth)
    ];
}