cal_days_in_month() 函数用于返回指定日历类型中,特定年份和月份的天数。
这个函数在处理日期计算、日历应用和日期验证时非常有用,特别是需要考虑闰年情况的场景。
cal_days_in_month(int $calendar, int $month, int $year): int
| 参数 | 描述 |
|---|---|
| calendar | 必需。指定要使用的日历类型。常用值:CAL_GREGORIAN(公历) |
| month | 必需。指定月份,范围1-12 |
| year | 必需。指定年份,如2024 |
返回指定月份中的天数。如果参数无效,返回false。
| 常量 | 描述 |
|---|---|
| CAL_GREGORIAN | 公历(格里高利历) |
| CAL_JULIAN | 儒略历 |
| CAL_JEWISH | 犹太历 |
| CAL_FRENCH | 法国共和历 |
// 获取2024年2月的天数(闰年)
$days = cal_days_in_month(CAL_GREGORIAN, 2, 2024);
echo "2024年2月有 {$days} 天";
输出结果:
2024年2月有 29 天
// 获取2023年2月的天数(非闰年)
$days = cal_days_in_month(CAL_GREGORIAN, 2, 2023);
echo "2023年2月有 {$days} 天";
输出结果:
2023年2月有 28 天
// 获取当前月份的天数
$currentYear = date('Y');
$currentMonth = date('n');
$days = cal_days_in_month(CAL_GREGORIAN, $currentMonth, $currentYear);
echo "当前月份有 {$days} 天";
// 显示2024年每个月的天数
$year = 2024;
echo "{$year}年各月份天数:\n";
for ($month = 1; $month <= 12; $month++) {
$days = cal_days_in_month(CAL_GREGORIAN, $month, $year);
echo "{$month}月: {$days}天\n";
}
输出结果:
2024年各月份天数:
1月: 31天
2月: 29天
3月: 31天
4月: 30天
5月: 31天
6月: 30天
7月: 31天
8月: 31天
9月: 30天
10月: 31天
11月: 30天
12月: 31天
| 返回值: | 返回指定月份中的天数(整数),失败返回false |
|---|---|
| PHP 版本: | 4.1+ |
| 依赖扩展: | 需要启用Calendar扩展 |
cal_days_in_month() 函数在以下场景中特别有用:
date() - 格式化本地时间/日期checkdate() - 验证日期的有效性mktime() - 取得一个日期的Unix时间戳strtotime() - 将任何英文文本的日期时间描述解析为Unix时间戳