Skip to content

PHP By Exalogics

A Simple Easy Site to Learn, Understand and create php

Menu
  • Home
  • Welcome to php by Exalogics
    • Introduction to PHP
    • How to Install PHP on Windows
    • PHP Variables
    • PHP Constants
    • PHP Switch Statement
    • PHP Data Types
    • PHP Operators
    • PHP If Else Statements
    • PHP E-Commerce Development
    • Your First PHP Script
    • PHP Error Handling
    • PHP Frameworks Guide
    • PHP MySQL Database Development
    • PHP Security Best Practices
    • PHP CMS Development
    • PHP Hosting Guide
  • PHP API Development
Menu

How to Work with Dates and Times in PHP

Posted on November 21, 2026






How to Work with Dates and Times in PHP – Complete Guide


How to Work with Dates and Times in PHP

Working with dates and times is a daily task for any PHP developer. Whether you’re building a blog, an e‑commerce platform, or a scheduling system, you’ll need to store, manipulate, and display dates accurately. This guide walks you through the modern DateTime API, timestamps, timezones, formatting, and best practices to keep your code reliable and future‑proof.

1. PHP Date & Time Basics

Before diving into the DateTime class, it’s helpful to understand the two fundamental concepts PHP uses for dates:

1.1 Timestamps

A timestamp is an integer representing the number of seconds that have elapsed since the Unix epoch (1970‑01‑01 00:00:00 UTC). It is timezone‑agnostic and ideal for storage and calculations.

1.2 Human‑Readable Strings

Human‑readable strings such as "2024-04-15 14:30:00" are convenient for display and input. PHP can convert between timestamps and formatted strings using functions like date(), strtotime(), and the DateTime class.

2. Introducing the DateTime Class

The DateTime class, introduced in PHP 5.2, provides an object‑oriented way to work with dates and times. It handles timezones, daylight‑saving changes, and complex arithmetic without the pitfalls of the older procedural functions.

2.1 Creating a DateTime Object

<?php
// Current date and time in the default timezone
$now = new DateTime(); 

// Specific date and time
$birthday = new DateTime('1990-07-12 08:30:00');

// Using a custom format string
$custom = DateTime::createFromFormat('d/m/Y H:i', '25/12/2024 18:45');
?>

2.2 Accessing Parts of a Date

Use the format() method to retrieve a formatted string, or the getTimestamp() method to get a Unix timestamp.

$now->format('Y-m-d H:i:s'); // 2026-11-21 14:05:00
$now->getTimestamp();        // 1479690300

3. Working with Timezones

Timezones are the most common source of bugs in date handling. The DateTimeZone class lets you attach a timezone to any DateTime object.

3.1 Setting a Specific Timezone

$tz = new DateTimeZone('America/New_York');
$nyTime = new DateTime('now', $tz);
echo $nyTime->format('Y-m-d H:i:s T'); // 2026-11-21 09:05:00 EST

3.2 Converting Between Timezones

$utc = new DateTime('now', new DateTimeZone('UTC'));
$utc->setTimezone(new DateTimeZone('Asia/Tokyo'));
echo $utc->format('Y-m-d H:i:s T'); // 2026-11-21 23:05:00 JST

4. Formatting Dates for Output

PHP’s format() method accepts a pattern of characters that represent parts of a date. Below are the most frequently used format characters:

Character Meaning
Y Four‑digit year (e.g., 2026)
m Month with leading zeros (01‑12)
d Day of month with leading zeros (01‑31)
H 24‑hour format (00‑23)
i Minutes (00‑59)
s Seconds (00‑59)
T Timezone abbreviation (e.g., UTC, EST)

4.1 Example: Blog Post Date

$postDate = new DateTime('2024-08-15 13:20:00', new DateTimeZone('Europe/London'));
echo $postDate->format('F j, Y \a\t g:i A'); // August 15, 2024 at 1:20 PM

5. Converting Between Formats

Often you’ll need to store a date in one format (e.g., ISO‑8601) while displaying it in another (e.g., “March 3, 2025”). The DateTime::createFromFormat() method makes this conversion straightforward.

5.1 From ISO‑8601 to Human‑Readable

format('l, F j, Y g:i A'); // Monday, March 3, 2025 2:30 PM

5.2 From Custom Input to Timestamp

getTimestamp(); // 1735684740

6. Performing Date Arithmetic

The DateInterval class and modify() method allow you to add or subtract time periods.

6.1 Adding Days, Months, or Years

modify('+1 month');      // 2024-02-01
$date->add(new DateInterval('P10D')); // 2024-02-11

6.2 Calculating the Difference Between Two Dates

diff($end);
echo $diff->format('%a days'); // 365 days

7. Storing Dates in Databases

When persisting dates, use the DATETIME or TIMESTAMP column types in MySQL/PostgreSQL. Store dates in UTC to avoid timezone confusion, then convert to the user’s local timezone when displaying.

// Example PDO insertion
$pdo = new PDO($dsn, $user, $pass);
$stmt = $pdo->prepare('INSERT INTO events (title, start_at) VALUES (:title, :start_at)');
$eventDate = (new DateTime('2024-07-04 18:00', new DateTimeZone('America/Los_Angeles')))
                ->setTimezone(new DateTimeZone('UTC'))
                ->format('Y-m-d H:i:s');
$stmt->execute(['title' => 'Independence Day Party', 'start_at' => $eventDate]);

8. Common Pitfalls & How to Avoid Them

  • Mixing timestamps with formatted strings: Always convert to a DateTime object before performing arithmetic.
  • Neglecting timezones: Store in UTC, convert on output. Use DateTimeZone explicitly.
  • Using deprecated functions: Functions like mktime() still work but lack timezone awareness. Prefer DateTime.
  • Incorrect format strings: Double‑check your createFromFormat() pattern; a missing “/” or “:” will cause false returns.

9. Best Practices Checklist

  1. Always instantiate DateTime with an explicit timezone.
  2. Store dates in UTC in your database.
  3. Use format() for display; never concatenate strings manually.
  4. Validate user input with DateTime::createFromFormat() and check getLastErrors().
  5. Leverage DateInterval for adding/subtracting periods.
  6. Write unit tests for any date‑related logic, especially around daylight‑saving transitions.

10. Conclusion

PHP offers a powerful, flexible set of tools for handling dates and times. By mastering the DateTime class, DateTimeZone, and related functions, you can avoid common bugs, support global users, and keep your code clean and maintainable. Apply the best‑practice checklist above, and you’ll be ready to build robust applications that get time right—every time.