使用 date('z') 可以获取当前日期在一年中的第几天(0-365)。若需针对特定日期计算,可结合 strtotime() 将目标时间字符串转换为时间戳后传入 date()。该方法基于格里高利历,自动处理闰年导致的2月天数差异,无需手动判断年份属性。

date('z') 对当前日期的返回值是什么
date('z') 返回的是从0开始的索引值,即1月1日返回0,12月31日在非闰年返回364,在闰年返回365。这意味着它直接对应数组下标式的“第几天”概念,而非人类习惯的1-based计数。

<?php
// 获取当前时间的年内第几天(0-indexed)
$current_day_of_year = date('z');
echo "Today is day: " . $current_day_of_year;
// 示例:固定日期测试
$fixed_date = '2023-03-01';
$day_index = date('z', strtotime($fixed_date));
echo "2023-03-01 is day: " . $day_index; // Output: 59
$leap_date = '2024-03-01';
$leap_day_index = date('z', strtotime($leap_date));
echo "2024-03-01 is day: " . $leap_day_index; // Output: 60
?>
上述代码展示了非闰年与闰年在3月1日的差异。2023年2月只有28天,因此3月1日是第60天(索引59);2024年是闰年,2月有29天,3月1日是第61天(索引60)。这验证了 date('z') 内部已处理闰年逻辑。
立即学习“PHP免费学习笔记(深入)”;
使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。
strtotime() 解析不同格式输入时的行为差异
strtotime() 能够解析多种自然语言和时间格式字符串,但在处理模糊日期时需注意时区影响。默认情况下,它使用脚本执行时的服务器时区。若未显式设置时区,跨时区部署可能导致结果偏差。

<?php
// 设置时区以确保一致性
date_default_timezone_set('Asia/Shanghai');
// 测试不同格式的输入
$formats = [
'2023-12-31',
'Dec 31, 2023',
'last day of 2023',
'tomorrow' // 相对时间
];
foreach ($formats as $fmt) {
$timestamp = strtotime($fmt);
if ($timestamp !== false) {
$day_of_year = date('z', $timestamp);
echo "Format: '$fmt' -> Day index: $day_of_year\n";
} else {
echo "Format: '$fmt' -> Failed to parse\n";
}
}
// 对比 UTC 时区下的结果
date_default_timezone_set('UTC');
$utc_timestamp = strtotime('2023-12-31');
$utc_day = date('z', $utc_timestamp);
echo "UTC 2023-12-31 is day: $utc_day";
?>
该段代码演示了 strtotime() 对标准日期、英文文本和相对时间的解析能力。同时通过切换时区展示了时区对时间戳转换的影响。在实际应用中,建议始终显式设置时区以避免不可预知的偏移。
如何获取1-based的第几天以符合业务需求
由于 date('z') 返回的是0-based索引,而许多业务场景需要1-based的序号(如1月1日为第1天),只需在结果上加1即可。这种转换简单且无性能损耗,适用于报表生成、序列表展示等场景。
<?php
// 获取1-based的年内第几天
$day_of_year_1based = date('z') + 1;
echo "Current day of year (1-based): " . $day_of_year_1based;
// 针对特定日期
$target = '2023-01-01';
$target_day = date('z', strtotime($target)) + 1;
echo "2023-01-01 is day: " . $target_day; // Output: 1
$target_leap = '2024-12-31';
$target_leap_day = date('z', strtotime($target_leap)) + 1;
echo "2024-12-31 is day: " . $target_leap_day; // Output: 366
?>
此方法确保了输出符合人类直觉。例如,2024年12月31日是闰年的最后一天,date('z') 返回365,加1后为366,准确反映了闰年有366天的事实。这种简单的算术操作避免了手动计算月份天数的复杂性,是推荐的最佳实践。


















