PHP日期时间区间与周期计算
PHP日期时间区间与周期计算
日期区间和周期计算在业务中很常用。比如统计某段时间的数据、生成时间序列。今天说说PHP中日期区间和周期的计算。
DatePeriod可以生成时间序列。
```php
$start = new DateTime('2024-01-01');
$end = new DateTime('2024-01-10');
$interval = new DateInterval('P1D');
$period = new DatePeriod($start, $interval, $end);
echo "日期范围:\n";
foreach ($period as $date) {
echo $date->format('Y-m-d') . "\n";
}
// 按周生成
$weekStart = new DateTime('2024-01-01');
$weekEnd = new DateTime('2024-03-31');
$weekInterval = DateInterval::createFromDateString('1 week');
$weeks = new DatePeriod($weekStart, $weekInterval, $weekEnd);
echo "周范围:\n";
foreach ($weeks as $week) {
echo "周开始: " . $week->format('Y-m-d') . "\n";
}
?>
计算两个日期之间的差值。
```php
function dateDiffInDays(string $start, string $end): int
{
$start = new DateTime($start);
$end = new DateTime($end);
return (int)$start->diff($end)->days;
}
function calculateAge(string $birthDate): int
{
return (new DateTime($birthDate))->diff(new DateTime())->y;
}
function getBusinessDays(string $start, string $end): array
{
$start = new DateTime($start);
$end = (new DateTime($end))->modify('+1 day');
$interval = new DateInterval('P1D');
$period = new DatePeriod($start, $interval, $end);
$businessDays = [];
foreach ($period as $date) {
if ($date->format('N') < 6) {
$businessDays[] = $date->format('Y-m-d');
}
}
return $businessDays;
}
echo "相差天数: " . dateDiffInDays('2024-01-01', '2024-12-31') . "\n";
echo "年龄: " . calculateAge('1995-06-15') . "\n";
echo "工作日: " . implode(', ', getBusinessDays('2024-01-01', '2024-01-10')) . "\n";
?>
日期区间查询在数据库中的应用。
```php
function queryByDateRange(PDO $pdo, string $startDate, string $endDate): array
{
$stmt = $pdo->prepare("
SELECT DATE(created_at) as date, COUNT(*) as count
FROM orders
WHERE created_at >= ? AND created_at < ?
GROUP BY DATE(created_at)
ORDER BY DATE(created_at)
");
$stmt->execute([$startDate, $endDate]);
$results = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
// 填充没有数据的日期
$start = new DateTime($startDate);
$end = new DateTime($endDate);
$period = new DatePeriod($start, new DateInterval('P1D'), $end);
$complete = [];
foreach ($period as $date) {
$key = $date->format('Y-m-d');
$complete[$key] = $results[$key] ?? 0;
}
return $complete;
}
?>
季度和年度的计算。
```php
function getQuarterRange(int $year, int $quarter): array
{
$startMonth = ($quarter - 1) * 3 + 1;
$start = new DateTime("{$year}-{$startMonth}-01");
$end = (clone $start)->modify('+3 months -1 day');
return ['start' => $start->format('Y-m-d'), 'end' => $end->format('Y-m-d')];
}
function getYearRange(int $year): array
{
return [
'start' => "{$year}-01-01",
'end' => "{$year}-12-31",
];
}
for ($q = 1; $q <= 4; $q++) {
$range = getQuarterRange(2024, $q);
echo "Q{$q}: {$range['start']} ~ {$range['end']}\n";
}
?>
日期区间的统计在报表和数据可视化中很常见。DatePeriod类配合DateTime可以灵活处理各种时间序列。填充没有数据的日期是生成完整报表的关键技巧。
