1. What are the basics of handling “Date and Time” in PHP?

In website and application development, situations that involve handling “dates” and “times” appear very frequently. For example, the posting date and time of a blog article, new arrival notifications for news, countdowns for limited-time campaigns, or automatic year updates for copyright notices.

PHP is a programming language that excels at such date and time processing, but there are broadly two approaches.

Two Approaches to Date Processing

When dealing with date and time in PHP, there are mainly the following two ways of writing code.

  • Function-Based (Procedural): This is the old way of writing, using functions like date() and time(). It is simple and easy to write, but not suitable for complex calculations.
  • Object-Oriented: This is the current mainstream way of writing, using the DateTime class. It offers flexible handling of date calculations and time zones (time differences), and is generally recommended for practical use.

In this article, we will explain both the easy-to-use function-based approach and the more practical DateTime class, in a way that is easy for beginners to understand.

2. [Practical] How to get and display the current date and time in PHP

First, let’s look at the absolute basics: how to get the “current time” and display it on the screen.

Basic Display Using the date() Function

The simplest method is to use the date() function. You only need to specify “in what format you want to display it” in the arguments (data passed to the function).

<?php
// Output the current date and time in 'Year-Month-Day Hour:Minute:Second' format
echo date('Y-m-d H:i:s');
// Output example: 2023-10-05 14:30:00
?>

With just this one line, the date and time at the moment of access will be displayed.

Modern Notation Using the DateTime Class

When using the DateTime class, which is frequently used in practice, you write it as follows.

<?php
// Create an instance (object) of the DateTime class
$now = new DateTime();

// Specify the display format using the format method
echo $now->format('Y-m-d H:i:s');
// Output example: 2023-10-05 14:30:00
?>

Although the description is a bit longer, the true value of the DateTime class is demonstrated when performing “date calculations” and other tasks discussed later. For now, remember that you can create the current time with new DateTime().

3. What is a “Timestamp”? The Mechanism for Manipulating Dates and Times

When handling dates and times in programming, the concept of “UNIX Timestamp” is unavoidable.

The Mechanism of a Timestamp (UNIX Time)

While we humans recognize dates and times as “October 5, 2023,” computers manage time by the number of seconds elapsed since “January 1, 1970, 00:00:00 (UTC).” This enormous number of seconds is called a “UNIX Timestamp.”

For example, a number like “1696486200” is a timestamp.

Internally, PHP performs calculations using this number and converts it to a human-readable format (like the date function) just before display.

How to use time() and strtotime()

These are the representative functions for handling timestamps.

  • time(): Gets the current timestamp (number of seconds).
  • strtotime(): Converts a string to a timestamp.
<?php
// Display the current timestamp
echo time(); // Output example: 1696486200 (changes with each access)

// Get the timestamp for the specified date and time
echo strtotime('2024-01-01 00:00:00');
?>

When calculating the “date next week” or “yesterday’s date,” understanding this timestamp mechanism makes the process very smooth.

4. Formatting Dates and Times! How to Arrange the Display Format as Desired

Even if a date is stored in the database as 2023-10-05 14:30:00, there are cases where you want to display it on the screen as “October 5, 2023.” This process is called “formatting.”

List of Frequently Used Format Specifiers

By combining the alphabetical symbols (format specifiers) used within the date() function and format() method, you can change the display freely.

記号MeaningOutput Example
Y4-digit year2023
y2-digit year23
mMonth (with leading 0)01, 10
nMonth (without leading 0)1, 10
dDay (with leading 0)05, 31
jDay (without leading 0)5, 31
HHour (24-hour format)09, 14
iMinute05, 59
sSecond00, 59
wDay of the week (numeric 0=Sun to 6=Sat)0, 1…

Usage Example:

<?php
$date = new DateTime('2023-10-05 14:30:00');

// Format into Japanese style
echo $date->format('Y年n月j日 H時i分');
// Output: 2023年10月5日 14時30分
?>

[Tips] Techniques for Displaying Japanese Days of the Week

PHP’s standard functions alone will output the day of the week in English (e.g., Monday) or as a number. It is common to use an array to display Japanese days of the week like “月曜日” (Monday).

<?php
$week = ['日', '月', '火', '水', '木', '金', '土'];
$date = new DateTime();

// Use 'w' to get the day of the week number (0-6) and map it to the array
$w = $date->format('w');
echo $date->format('Y年m月d日') . '(' . $week[$w] . ')';
// Output example: 2023年10月05日(木)
?>

5. The Time Zone Wall: How to Handle International Time

When uploading a PHP program to a server, you may encounter a problem where “the time is off by 9 hours.” This is caused by the time zone setting.

Japan Standard Time (JST) and Coordinated Universal Time (UTC)

If the server is set to Coordinated Universal Time (UTC), the time will be displayed 9 hours later than Japan Standard Time (JST). When creating a website for Japan, you need to explicitly set “Japan Standard Time.”

How to Set the Time Zone

The simplest solution is to perform the following setting at the beginning of the PHP file.

<?php
// Set the time zone to Tokyo (Japan)
date_default_timezone_set('Asia/Tokyo');
echo date('Y-m-d H:i:s');
// This will display the correct Japan time
?>

Also, if you are in an environment where you can edit the configuration file named php.ini, you can change the setting in the file itself, eliminating the need to write the code every time.

6. Master Date Calculation and Comparison! Challenge Advanced Processing

We will explain the methods for calculation and comparison needed when you want to “get the date 3 days from now” or “determine if it is during a campaign period.” Here we utilize the convenient DateTime class.

Addition/Subtraction of Days (Calculating “X days later”)

By using the modify() method, you can manipulate dates with intuitive phrases.

<?php
$date = new DateTime('2023-10-01');

// Add 1 day (the next day)
$date->modify('+1 day');
echo $date->format('Y-m-d'); // 2023-10-02

// Subtract 1 month (last month)
$date->modify('-1 month');
echo $date->format('Y-m-d'); // 2023-09-02
?>

Comparing Two Dates

DateTime objects can be compared using comparison operators (>, <, etc.), just like ordinary numbers.

<?php
$today = new DateTime(); // Now
$target_day = new DateTime('2024-01-01'); // New Year's Day

if ($today < $target_day) {
echo "New Year's Day is still ahead.";
} else {
echo "New Year's Day has passed!";
}
?>

In this way, with an object-oriented approach, complex date calculations can also be written very simply.

7. Beware of Deprecated Functions! How to Choose Safe Date and Time Functions

Finally, here are some points to keep in mind when looking at old articles or reference books. With PHP version updates, some functions have become “deprecated” (will be unusable in the future).

strftime() Deprecated in PHP 8.1 and Later

The function strftime(), which was frequently used for date formatting, became deprecated in PHP 8.1 and later. If you see it in old code, you need to rewrite it to use the date() function or DateTime::format() as explained in this article.

DateTime Class is Recommended for Modern Development

If you are starting to learn PHP, we strongly recommend getting into the habit of primarily using the DateTime class (and DateTimeImmutable class). The main reasons for this recommendation are the following two points.

  • Avoiding the 2038 Problem: Older systems may not be able to handle dates correctly after 2038, but the DateTime class addresses this issue in a 64-bit environment.
  • Improved Readability: The code becomes easier to read and maintain.

Date and time manipulation is a fundamental yet profound area of web development. For now, be sure to grasp the basic patterns of “getting, displaying, and calculating.”