PHP Calendar
Learn how to work with dates, times, and calendars in PHP using date(), mktime(), strtotime(), and the DateTime class, with examples and best practices.
Introduction
This chapter covers how to work with dates, times, and calendars in PHP. You will learn the core date and time functions, how to build a calendar grid for a given month, and the best practices that keep date logic correct across time zones. Each example is small and runnable so you can paste it straight into a PHP file.
For a deeper look at individual topics, see the related chapters on PHP Date and Time, the date() function, and PHP Time Zones.
Understanding PHP Date and Time Functions
PHP provides a robust set of date and time functions for formatting, calculating, and manipulating dates, times, and time zones. These functions are essential for applications that need to work with temporal data such as schedulers, booking systems, and, of course, calendars.
PHP also ships a separate Calendar Extension (cal_days_in_month(), jdtogregorian(), and friends) for converting between calendar systems like Julian, Gregorian, and Jewish. The two are often confused: the Calendar Extension converts between systems, while the date/time functions below handle everyday formatting and arithmetic. Most "build a calendar" tasks only need the date/time functions.
Common PHP Date and Time Functions
date()– Formats a local date and time string according to a specified format.echo date("Y-m-d H:i:s"); // Outputs: 2023-10-25 14:30:00mktime()– Creates a Unix timestamp for a specified date and time.Note:echo mktime(14, 30, 0, 10, 25, 2023); // Outputs: 1698237000mktime()relies on the server's default timezone. For reproducible results, explicitly set a timezone usingdate_default_timezone_set()orDateTimeZone.strtotime()– Parses an English textual datetime string into a Unix timestamp.echo strtotime("now"); // Outputs: current timestamp echo strtotime("+1 day"); // Outputs: timestamp for tomorrowtime()– Returns the current Unix timestamp.echo time(); // Outputs: current timestampDateTime&DateTimeImmutable– Object-oriented classes for safer date/time manipulation and formatting.$dt = new DateTime('2023-10-25 14:30:00'); echo $dt->format('Y-m-d H:i:s');
In addition to these functions, there are many others for manipulating dates and times. Understanding how they work lets you create efficient and reliable PHP applications.
How Many Days Are in a Month?
A common calendar task is finding the number of days in a given month, which varies and depends on leap years for February. There are two reliable ways to do this:
// Using the Calendar Extension (requires ext-calendar)
echo cal_days_in_month(CAL_GREGORIAN, 2, 2024); // Outputs: 29 (2024 is a leap year)
// Using date() with the 't' format character (no extension needed)
echo date('t', mktime(0, 0, 0, 2, 1, 2024)); // Outputs: 29The date('t', ...) approach is portable because it does not depend on the Calendar Extension being installed.
Building a Simple Calendar for a Month
Putting the pieces together, here is how to print the days of a month aligned under weekday columns. We find the first weekday of the month with date('w', ...) (0 = Sunday) and the day count with date('t', ...):
$month = 10;
$year = 2023;
$firstDayTimestamp = mktime(0, 0, 0, $month, 1, $year);
$daysInMonth = (int) date('t', $firstDayTimestamp);
$startWeekday = (int) date('w', $firstDayTimestamp); // 0 = Sunday
echo "Su Mo Tu We Th Fr Sa\n";
// Pad the first row so day 1 lands under the correct weekday.
echo str_repeat(' ', $startWeekday);
for ($day = 1; $day <= $daysInMonth; $day++) {
printf('%2d ', $day);
// Break to a new line after Saturday.
if (($startWeekday + $day) % 7 === 0) {
echo "\n";
}
}
echo "\n";This loop prints October 2023 as a calendar grid. To learn more about the loop used here, see PHP Loops.
Best Practices for Using PHP Date and Time Functions
When using PHP date and time functions, it's important to follow best practices to ensure that your applications are efficient and effective. Here are some tips to keep in mind:
- Prefer
DateTimeandDateTimeImmutableobjects over procedural functions for better readability and built-in timezone safety. - Always set an explicit timezone using
DateTimeZoneordate_default_timezone_set()to prevent unexpected shifts during daylight saving time or server migrations. - Validate parsed dates using
DateTime::getLastErrors()to catch invalid input early and avoid silent failures. - Cache computed timestamps or formatted strings in tight loops to reduce function call overhead.
Conclusion
PHP's date and time functions are an essential part of any PHP application that needs to work with temporal data. By understanding how these functions work and following best practices, you can develop reliable and efficient applications.