Back to Blog
Lesson 47 of the PHP: Modern PHP from the Ground Up course
PHPSeptember 4, 20263 min read

Working with Dates and Time in PHP: The DateTime Class

Master PHP dates and timezones with the DateTime class. Learn to format outputs, convert timezones, and avoid common traps in your MVC application.

PHPDateTimeBackendTimezonesOOP
A close-up of a calendar page with a pink push pin, pencil, and binder clip on an orange background.

Previously in this course, we explored building a simple authentication system, which often requires tracking when users last logged in or when their accounts were created. In this lesson, we move beyond simple timestamps and master the DateTime class to handle dates and timezones with precision.

Why Avoid Legacy Date Functions?

In older PHP code, you might see functions like date() or strtotime(). These are functional, but they lack the object-oriented control required for complex applications. They often rely on global state (like the default timezone set in php.ini), making them difficult to test and prone to silent errors during timezone conversions.

The DateTime class is the modern standard. It encapsulates a point in time, its associated timezone, and provides methods to manipulate that time without affecting the rest of your application's configuration.

Using the DateTime Class

The DateTime class represents a specific moment. When you instantiate it, it defaults to "now," but you can pass any valid date string to the constructor.

PHP
#6A9955">// Creating a new instance
$now = new DateTime();

#6A9955">// Creating a specific date
$eventDate = new DateTime('2023-12-25 10:00:00');

#6A9955">// Formatting for display
echo $eventDate->format('Y-m-d H:i:s'); #6A9955">// Outputs: 2023-12-25 10:00:00

The format() method uses standard characters:

  • Y: 4-digit year (e.g., 2023)
  • m: Month with leading zeros (01-12)
  • d: Day with leading zeros (01-31)
  • H: 24-hour format (00-23)
  • i: Minutes (00-59)
  • s: Seconds (00-59)

Handling Timezone Conversions

In a real-world MVC app, you typically store dates in UTC in the database, then convert them to the user's local timezone for display. PHP handles this through the DateTimeZone class.

PHP
#6A9955">// 1. Define the UTC time(database format)
$utcDate = new DateTime('2023-12-25 10:00:00', new DateTimeZone('UTC'));

#6A9955">// 2. Create the target timezone
$userTimezone = new DateTimeZone('America/New_York');

#6A9955">// 3. Convert
$utcDate->setTimezone($userTimezone);

echo $utcDate->format('Y-m-d H:i:s T'); 
#6A9955">// Outputs: 2023-12-25 05:00:00 EST

This ensures your logic remains consistent. You never change the actual time in the database; you only change the view of that time.

Integrating Dates into the MVC Project

In our running project, let's update our User model to format the created_at timestamp.

PHP
#6A9955">// In your User Model
public function getFormattedCreatedAt(): string
{
    $date = new DateTime($this->createdAt);
    $date->setTimezone(new DateTimeZone('UTC'));
    return $date->format('M j, Y'); #6A9955">// e.g., Dec 25, 2023
}

By keeping this logic in the Model, your controllers stay clean, and your views consistently display dates in the format you prefer.

Hands-on Exercise

  1. Create a PHP script that instantiates a DateTime object for "next Friday."
  2. Convert that object to the timezone 'Asia/Tokyo'.
  3. Echo the result in a human-readable format like d/m/Y H:i.
  4. Hint: Use modify() to change the date of an existing instance.

Common Pitfalls

  • Ignoring Timezones: Never assume your server's local time matches the user's. Always store in UTC and handle conversion at the last possible second (the View layer).
  • Mutating Objects: Methods like setTimezone() modify the original object. If you need the original date later, clone the object first: $newDate = clone $date;.
  • Invalid Formats: Passing a nonsense string to the DateTime constructor will throw an Exception. In later lessons, we will cover how to handle these using try-catch blocks.

FAQ

Q: Can I compare two dates? A: Yes! You can compare DateTime objects using standard comparison operators like <, >, or ==. PHP will compare the underlying timestamps.

Q: Where can I see all supported timezones? A: You can use DateTimeZone::listIdentifiers() to get a complete array of all supported timezone strings in PHP.

Recap

We’ve learned that DateTime provides a robust, object-oriented way to handle time. By using DateTimeZone for conversions and format() for display, you can avoid common timezone bugs. Always keep your core data in UTC and only worry about local formatting when presenting data to the user, similar to how we handle Working with JSON APIs to ensure clean data transfer.

Up next: We will tackle robust error handling with Exceptions to make our code more resilient.

Similar Posts