PHP Calendar

Calendar functions: days in a month, Julian day conversion, Easter dates.

Intermediate
Key PointsThe Calendar extension covers Gregorian, Julian, Jewish and French Republican calendars.

Functions

FunctionPurpose
cal_days_in_month某年某月有多少天
cal_info历法信息(月份名等)
cal_to_jd历法日期转儒略日
cal_from_jd儒略日转历法日期
easter_date某年复活节的时间戳
easter_days复活节距 3 月 21 日的天数
gregoriantojd公历转儒略日
jdtogregorian儒略日转公历
jddayofweek星期几
jdmonthname月份名
jdtojulian儒略日转儒略历

Month length and Easter

PHP
<?php
date_default_timezone_set("Asia/Shanghai");

echo cal_days_in_month(CAL_GREGORIAN, 2, 2024), "\n";
echo cal_days_in_month(CAL_GREGORIAN, 2, 2023), "\n";
echo cal_days_in_month(CAL_GREGORIAN, 4, 2023), "\n";

echo date("Y-m-d", easter_date(2024)), "\n";
echo easter_days(2024), "\n";
Output
29
28
30
2024-03-31
10

easter_days(2024) returns 10 — Easter is 10 days after 21 March, i.e. 31 March. It is timezone-independent, unlike easter_date.

easter_date() relies on Unix timestamps — unusable before 1970 or after 2037. Use easter_days() for wide ranges.

Julian day

Julian Day is a continuous day count starting 4713 BC. It is the natural pivot for cross-calendar arithmetic.

PHP
<?php
$jd = gregoriantojd(11, 15, 2023);
echo $jd, "\n";

echo jdtogregorian($jd), "\n";
echo jdtojulian($jd), "\n";

echo jddayofweek($jd, 0), " ", jddayofweek($jd, 1), " ", jddayofweek($jd, 2), "\n";
echo jdmonthname($jd, 1), "\n";

// 日期差直接用减法
$jd2 = gregoriantojd(12, 25, 2023);
echo $jd2 - $jd, "\n";
Output
2460264
11/15/2023
11/2/2023
3 Wednesday Wed
November
40

The same Julian Day is 11/15/2023 in Gregorian and 11/2/2023 in Julian — 13 days apart. That is why historical dates must name their calendar.

Modejddayofweekjdmonthname
00-6(周日为 0)缩写月名
1英文全名全称月名
2英文缩写儒略历缩写
3—儒略历全称

Calendar constants

ConstantCalendar
CAL_GREGORIAN公历(现行)
CAL_JULIAN儒略历
CAL_JEWISH犹太历
CAL_FRENCH法国共和历
CAL_NUM_CALS支持的历法数量
PHP
<?php
$jd = cal_to_jd(CAL_JEWISH, 1, 1, 5784);
echo $jd, "\n";

$d = cal_from_jd($jd, CAL_GREGORIAN);
echo $d["date"], "\n";
echo $d["monthname"], "\n";

echo cal_info(CAL_GREGORIAN)["months"][11], "\n";
Output
2460292
9/16/2023
September
November
cal_from_jd returns date, month, day, year, dow, day names and month names. Using date is more reliable than manual formatting.

Practical uses

  • Month-end closing —— cal_days_in_month instead of hardcoding 28/30/31
  • Scheduling —— jddayofweek to detect weekends
  • Holiday maths —— Easter, Thanksgiving-style nth-weekday rules
  • Historical dates —— pre-1582 dates need an explicit calendar
Everyday work needs only DateTime. The Calendar extension is for non-Gregorian calendars and religious holidays. date("t") already gives days in month.

Friends & Partners