PHP 怎么PHP日期助手

wen PHP项目 1

我来为您创建一个功能比较完整的 PHP 日期助手类,包含常用的日期处理功能:

PHP 怎么PHP日期助手

<?php
class DateHelper
{
    /**
     * 格式化日期
     * @param string|int $date 日期字符串或时间戳
     * @param string $format 格式
     * @return string
     */
    public static function format($date = null, $format = 'Y-m-d H:i:s')
    {
        if (is_numeric($date)) {
            return date($format, $date);
        }
        if (empty($date)) {
            return date($format);
        }
        return date($format, strtotime($date));
    }
    /**
     * 获取当前时间戳
     * @return int
     */
    public static function timestamp()
    {
        return time();
    }
    /**
     * 获取当前日期时间
     * @param string $format
     * @return string
     */
    public static function now($format = 'Y-m-d H:i:s')
    {
        return date($format);
    }
    /**
     * 日期加减
     * @param string $date 日期
     * @param int $days 天数
     * @param string $format 格式
     * @return string
     */
    public static function addDays($date, $days, $format = 'Y-m-d')
    {
        $timestamp = strtotime($date);
        $newTimestamp = strtotime("+{$days} days", $timestamp);
        return date($format, $newTimestamp);
    }
    /**
     * 日期加月
     * @param string $date 日期
     * @param int $months 月数
     * @param string $format 格式
     * @return string
     */
    public static function addMonths($date, $months, $format = 'Y-m-d')
    {
        $timestamp = strtotime($date);
        $newTimestamp = strtotime("+{$months} months", $timestamp);
        return date($format, $newTimestamp);
    }
    /**
     * 日期加年
     * @param string $date 日期
     * @param int $years 年数
     * @param string $format 格式
     * @return string
     */
    public static function addYears($date, $years, $format = 'Y-m-d')
    {
        $timestamp = strtotime($date);
        $newTimestamp = strtotime("+{$years} years", $timestamp);
        return date($format, $newTimestamp);
    }
    /**
     * 获取两个日期之间的天数差
     * @param string $date1
     * @param string $date2
     * @return int
     */
    public static function diffInDays($date1, $date2)
    {
        $timestamp1 = strtotime($date1);
        $timestamp2 = strtotime($date2);
        $diff = abs($timestamp1 - $timestamp2);
        return floor($diff / (60 * 60 * 24));
    }
    /**
     * 获取两个日期之间的完整天数差(向下取整)
     * @param string $date1
     * @param string $date2
     * @return int
     */
    public static function diffInWholeDays($date1, $date2)
    {
        $timestamp1 = strtotime(date('Y-m-d', strtotime($date1)));
        $timestamp2 = strtotime(date('Y-m-d', strtotime($date2)));
        $diff = ($timestamp1 - $timestamp2) / (60 * 60 * 24);
        return (int)$diff;
    }
    /**
     * 获取两个日期之间的月数差异
     * @param string $date1
     * @param string $date2
     * @return int
     */
    public static function diffInMonths($date1, $date2)
    {
        $timestamp1 = strtotime($date1);
        $timestamp2 = strtotime($date2);
        $year1 = date('Y', $timestamp1);
        $year2 = date('Y', $timestamp2);
        $month1 = date('n', $timestamp1);
        $month2 = date('n', $timestamp2);
        return ($year2 - $year1) * 12 + ($month2 - $month1);
    }
    /**
     * 获取相对时间(如:3分钟前,2小时前)
     * @param string|int $date
     * @return string
     */
    public static function relativeTime($date)
    {
        $timestamp = is_numeric($date) ? $date : strtotime($date);
        $diff = time() - $timestamp;
        $periods = [
            '秒前' => 1,
            '分钟前' => 60,
            '小时前' => 3600,
            '天前' => 86400,
            '周前' => 604800,
            '月前' => 2592000,
            '年前' => 31536000
        ];
        foreach ($periods as $period => $seconds) {
            if ($diff < $seconds) {
                return $diff . $period;
            }
        }
        return date('Y-m-d H:i:s', $timestamp);
    }
    /**
     * 判断是否为有效日期
     * @param string $date
     * @return bool
     */
    public static function isValid($date)
    {
        if (empty($date)) return false;
        try {
            $timestamp = strtotime($date);
            if ($timestamp === false) return false;
            // 检查日期格式
            $formattedDate = date('Y-m-d', $timestamp);
            $originalDate = date('Y-m-d', strtotime($date));
            return $formattedDate === $originalDate;
        } catch (Exception $e) {
            return false;
        }
    }
    /**
     * 获取日期的开始时间
     * @param string $date
     * @return string
     */
    public static function startOfDay($date = null)
    {
        $timestamp = $date ? strtotime($date) : time();
        return date('Y-m-d 00:00:00', $timestamp);
    }
    /**
     * 获取日期的结束时间
     * @param string $date
     * @return string
     */
    public static function endOfDay($date = null)
    {
        $timestamp = $date ? strtotime($date) : time();
        return date('Y-m-d 23:59:59', $timestamp);
    }
    /**
     * 获取月份开始和结束日期
     * @param string $date
     * @return array
     */
    public static function monthRange($date = null)
    {
        $timestamp = $date ? strtotime($date) : time();
        $start = date('Y-m-01', $timestamp);
        $end = date('Y-m-t', $timestamp);
        return ['start' => $start, 'end' => $end];
    }
    /**
     * 获取一周的开始和结束日期(周一为开始)
     * @param string $date
     * @return array
     */
    public static function weekRange($date = null)
    {
        $timestamp = $date ? strtotime($date) : time();
        $dayOfWeek = date('N', $timestamp); // 1-7, 周一为1
        $start = date('Y-m-d', strtotime('-'.($dayOfWeek - 1).' days', $timestamp));
        $end = date('Y-m-d', strtotime('+'.(7 - $dayOfWeek).' days', $timestamp));
        return ['start' => $start, 'end' => $end];
    }
    /**
     * 获取最近 N 天的日期列表
     * @param int $days 天数
     * @param bool $includeToday 是否包含今天
     * @return array
     */
    public static function recentDays($days = 7, $includeToday = true)
    {
        $dates = [];
        $start = $includeToday ? 0 : 1;
        $end = $days - ($includeToday ? 1 : 0);
        for ($i = 0; $i < $days; $i++) {
            $dates[] = date('Y-m-d', strtotime("-{$i} days"));
        }
        return $dates;
    }
    /**
     * 获取季度范围
     * @param string $date
     * @return array
     */
    public static function quarterRange($date = null)
    {
        $timestamp = $date ? strtotime($date) : time();
        $month = date('n', $timestamp);
        $quarter = ceil($month / 3);
        $startMonth = ($quarter - 1) * 3 + 1;
        $endMonth = $quarter * 3;
        $start = date('Y-m-01', mktime(0, 0, 0, $startMonth, 1, date('Y', $timestamp)));
        $end = date('Y-m-t', mktime(0, 0, 0, $endMonth, 1, date('Y', $timestamp)));
        return ['start' => $start, 'end' => $end];
    }
    /**
     * 获取星期几(中文)
     * @param string $date
     * @return string
     */
    public static function dayOfWeek($date = null)
    {
        $timestamp = $date ? strtotime($date) : time();
        $days = ['日', '一', '二', '三', '四', '五', '六'];
        return $days[date('w', $timestamp)];
    }
    /**
     * 获取两个日期之间的所有日期
     * @param string $startDate
     * @param string $endDate
     * @return array
     */
    public static function dateRange($startDate, $endDate)
    {
        $dates = [];
        $start = strtotime($startDate);
        $end = strtotime($endDate);
        while ($start <= $end) {
            $dates[] = date('Y-m-d', $start);
            $start = strtotime('+1 day', $start);
        }
        return $dates;
    }
    /**
     * 人性化日期显示
     * @param string $date
     * @return string
     */
    public static function humanize($date)
    {
        $timestamp = strtotime($date);
        $diff = time() - $timestamp;
        if ($diff < 60) {
            return $diff . '秒前';
        } elseif ($diff < 3600) {
            return floor($diff / 60) . '分钟前';
        } elseif ($diff < 86400) {
            return floor($diff / 3600) . '小时前';
        } elseif ($diff < 604800) {
            return floor($diff / 86400) . '天前';
        } elseif ($diff < 2592000) {
            return floor($diff / 604800) . '周前';
        } else {
            return date('Y-m-d H:i', $timestamp);
        }
    }
    /**
     * 获取日期的时间戳
     * @param string $date
     * @return int
     */
    public static function toTimestamp($date)
    {
        return strtotime($date);
    }
    /**
     * 检查日期是否在范围内
     * @param string $date 要检查的日期
     * @param string $startDate 开始日期
     * @param string $endDate 结束日期
     * @return bool
     */
    public static function isInRange($date, $startDate, $endDate)
    {
        $timestamp = strtotime($date);
        $start = strtotime($startDate);
        $end = strtotime($endDate);
        return $timestamp >= $start && $timestamp <= $end;
    }
}
// 使用示例
/*
// 格式化日期
echo DateHelper::format(); // 当前时间
echo DateHelper::format('2024-01-15'); 
echo DateHelper::format(1705315200);
// 日期计算
echo DateHelper::addDays('2024-01-01', 10); // 2024-01-11
echo DateHelper::addMonths('2024-01-01', 2); // 2024-03-01
echo DateHelper::addYears('2024-01-01', 1); // 2025-01-01
// 日期差
echo DateHelper::diffInDays('2024-01-01', '2024-01-10'); // 9
echo DateHelper::diffInMonths('2023-01-01', '2024-03-01'); // 14
// 相对时间
echo DateHelper::relativeTime(time() - 300); // 5分钟前
// 范围获取
print_r(DateHelper::weekRange());
print_r(DateHelper::monthRange());
// 其他功能
echo DateHelper::dayOfWeek('2024-01-15'); // 一
print_r(DateHelper::dateRange('2024-01-01', '2024-01-05'));
*/
?>

这个日期助手类提供了以下主要功能:

  1. 基础功能:格式化、时间戳转换
  2. 日期计算:加减天数/月数/年数
  3. 日期比较:计算日期差(天/月)
  4. 范围获取:周/月/季度范围
  5. 人性化:相对时间、中文星期
  6. 工具方法:有效性验证、日期范围生成

使用方式:

// 直接调用静态方法
echo DateHelper::format();
echo DateHelper::addDays('2024-01-01', 10);

您可以根据实际需求调整或扩展这些方法。

抱歉,评论功能暂时关闭!