SOLARISE
DEV

PHP DateTime Functions: Formatting and Manipulating Dates & Times

Master date and time handling in your PHP projects

Originally published: December 15th, 2017. Updated on: April 29th, 2025.

When working with PHP, especially on applications like forums, blogs, or discussion boards where date and time information is important, you'll often need to display dates and times in various formats or perform calculations. PHP includes a range of functions to help you easily format and adjust date/time displays. Actually, PHP's DateTime handling is quite powerful once you get the hang of it.

This tutorial will look at some easy ways to handle date and time information using PHP's built-in functions and the DateTime object (which is generally preferred in modern PHP).

Converting PHP DateTime Representations to Strings

The Old Way: time() and date()

One of the simplest, older date/time functions in PHP is time(). It takes no arguments and returns the current Unix timestamp – the number of seconds that have elapsed since the "Unix Epoch" (January 1st, 1970 at 00:00:00 Coordinated Universal Time (UTC)). Basically, it's a standard reference point for time calculations.

<?php
$timestamp = time();
echo $timestamp; // Outputs something like: 1714379160
?>

While useful internally, this raw number isn't very human-readable. That's where the date() function comes in. It formats a Unix timestamp into a more readable date and time string.

The date() function takes two main arguments:

  1. A format string specifying how the output should look.
  2. An optional Unix timestamp (if omitted, it uses the current time, like time()).
<?php
$timestamp = 1219075172; // Example timestamp (August 18, 2008, 4:59 pm UTC)
// Format: Month Day, Year, Hour:Minute am/pm
echo date("F j, Y, g:i a", $timestamp); // Outputs: August 18, 2008, 4:59 pm
?>

The format string uses specific characters that date() replaces with corresponding date/time parts:

  • F: Full textual representation of a month (e.g., August)
  • j: Day of the month without leading zeros (e.g., 1, 18, 31)
  • Y: A full numeric representation of a year, 4 digits (e.g., 2008, 2025)
  • g: 12-hour format of an hour without leading zeros (e.g., 1, 12)
  • i: Minutes with leading zeros (e.g., 00, 05, 59)
  • a: Lowercase Ante meridiem and Post meridiem (am or pm)

You can find a full list of format characters on PHP.net. You can add other text to the format string, but remember to escape any characters that have special meaning in the format string if you want them to appear literally (using a backslash \).

Creating Timestamps: mktime()

If you need a timestamp for a specific date and time (not the current time), the mktime() function can be used. It returns the Unix timestamp for a given date. Its arguments represent (in order): hour, minute, second, month, day, year.

<?php
// Hour, Minute, Second, Month, Day, Year
$specific_timestamp = mktime(10, 15, 0, 12, 12, 1980); // 10:15:00 on December 12, 1980
echo $specific_timestamp; // Outputs: 345464100 (timestamp may vary based on server timezone)

echo date("F j, Y, g:i a", $specific_timestamp); // Outputs: December 12, 1980, 10:15 am
?>

Important Note: time(), date(), and mktime() are older functions and can be confusing regarding timezones. mktime() especially assumes the local server timezone unless configured otherwise. It's just something to watch out for.

The Modern Way: The DateTime Object

Modern PHP strongly encourages using the object-oriented DateTime class (and related classes like DateTimeImmutable, DateTimeZone, DateInterval). This approach is more robust, explicit about timezones, and generally easier to work with for complex manipulations.

Creating DateTime Objects:

<?php
// Create a DateTime object for the current time
$now = new DateTime();
echo $now->format('Y-m-d H:i:s'); // Outputs current date and time, e.g., 2025-04-29 09:46:00

// Create a DateTime object for a specific date/time
$specific_date = new DateTime('1980-12-12 10:15:00');
echo $specific_date->format('F j, Y, g:i a'); // Outputs: December 12, 1980, 10:15 am

// Create from a specific timestamp
$timestamp = 1219075172;
$date_from_ts = new DateTime("@{$timestamp}"); // The '@' signifies a Unix timestamp
echo $date_from_ts->format('F j, Y, g:i a'); // Outputs: August 18, 2008, 4:59 pm

// Handling Timezones explicitly
$london_time = new DateTime('now', new DateTimeZone('Europe/London'));
$new_york_time = new DateTime('now', new DateTimeZone('America/New_York'));

echo "London: " . $london_time->format('Y-m-d H:i:s P') . "<br>";
echo "New York: " . $new_york_time->format('Y-m-d H:i:s P') . "<br>";
?>

Formatting with format():

The DateTime object uses the format() method, which accepts the same format characters as the date() function.

Modifying Dates with modify() or add()/sub():

The DateTime object makes modifications easy using methods like modify(), add(), and sub(). add() and sub() require a DateInterval object.

<?php
$date = new DateTime('2025-04-29');
echo "Original: " . $date->format('Y-m-d') . "<br>";

// Using modify() with relative formats
$date->modify('+1 day');
echo "Modified (+1 day): " . $date->format('Y-m-d') . "<br>"; // 2025-04-30

$date->modify('next monday');
echo "Modified (next monday): " . $date->format('Y-m-d') . "<br>"; // 2025-05-05

// Using add() and sub() with DateInterval
$date = new DateTime('2025-04-29');
$interval = new DateInterval('P2W'); // P2W = Period of 2 Weeks
$date->add($interval);
echo "Added 2 Weeks: " . $date->format('Y-m-d') . "<br>"; // 2025-05-13

$interval_month = new DateInterval('P1M'); // Period of 1 Month
$date->sub($interval_month);
echo "Subtracted 1 Month: " . $date->format('Y-m-d') . "<br>"; // 2025-04-13
?>

DateTimeImmutable:

For safer code where you don't want date objects to be changed accidentally, use DateTimeImmutable. Its modification methods (modify, add, sub) return a new DateTimeImmutable object instead of changing the original one. This is often a better approach.

<?php
$date_immutable = new DateTimeImmutable('2025-01-01');
$new_date = $date_immutable->modify('+1 month');

echo "Original: " . $date_immutable->format('Y-m-d') . "<br>"; // 2025-01-01 (unchanged)
echo "New: " . $new_date->format('Y-m-d') . "<br>";      // 2025-02-01
?>

Parsing Strings into Dates: strtotime() and DateTime::createFromFormat()

strtotime()

Sometimes you need to convert a human-readable date string into a timestamp or DateTime object. The strtotime() function attempts to parse various English textual datetime descriptions into a Unix timestamp.

<?php
// Examples run relative to April 29, 2025

$ts_friday = strtotime("next friday");
echo date("l, F j, Y", $ts_friday); // Outputs: Friday, May 2, 2025

$ts_tuesday = strtotime("last tuesday");
echo date("l, F j, Y", $ts_tuesday); // Outputs: Tuesday, April 22, 2025

$ts_future = strtotime("+3 years 2 months 1 day");
echo date("l, F j, Y", $ts_future); // Outputs: Wednesday, June 30, 2028

$ts_past = strtotime("5 weeks ago");
echo date("l, F j, Y", $ts_past); // Outputs: Tuesday, March 25, 2025

// Using it with DateTime
$date_obj = new DateTime();
$date_obj->setTimestamp(strtotime("+2 days"));
echo "Two days from now: " . $date_obj->format('Y-m-d'); // Outputs: 2025-05-01
?>

While flexible, strtotime() can be ambiguous and might not parse all formats correctly. It relies on English language descriptions and can sometimes produce unexpected results. For a full description of supported formats, check the GNU Date input formats documentation.

DateTime::createFromFormat()

A much more reliable way to parse date strings is using DateTime::createFromFormat(). You provide the exact format of the input string, making the parsing unambiguous.

<?php
$date_string = "25/12/2025 14:30";
$format = "d/m/Y H:i"; // Day/Month/Year Hour:Minute

$christmas_date = DateTime::createFromFormat($format, $date_string);

if ($christmas_date) {
    echo "Parsed Date: " . $christmas_date->format('Y-m-d H:i:s'); // Outputs: 2025-12-25 14:30:00
} else {
    echo "Failed to parse date string.";
}

// Example with different format
$date_string_us = "07-04-2026";
$format_us = "m-d-Y";
$july_4th = DateTime::createFromFormat($format_us, $date_string_us);
if ($july_4th) {
        echo "<br>US Date: " . $july_4th->format('F jS, Y'); // Outputs: July 4th, 2026
}
?>

Using createFromFormat is generally the recommended approach when you know the structure of the date string you need to parse.

Measuring Execution Time: microtime()

The microtime() function returns the current Unix timestamp with microseconds. It's primarily used for benchmarking code execution time, not typically for displaying dates.

It takes one optional boolean argument. If true, it returns the timestamp as a float; otherwise, it returns a string like "msec sec".

<?php
echo microtime();       // Outputs string like: 0.12345600 1714379160
echo "<br>";
echo microtime(true);   // Outputs float like: 1714379160.1234
?>

Example: Benchmarking Loops

<?php
$iterations = 10000000;

// --- While Loop ---
$while_start = microtime(true);
$count = 0;
while ($count < $iterations) {
    $count++;
}
$duration_while = (microtime(true) - $while_start) * 1000; // Duration in milliseconds
printf("While loop execution: %.3f ms<br>", $duration_while);

// --- For Loop ---
$for_start = microtime(true);
$count = 0; // Reset count
for ($i = 0; $i < $iterations; $i++) {
    $count++;
}
$duration_for = (microtime(true) - $for_start) * 1000; // Duration in milliseconds
printf("For loop execution: %.3f ms<br>", $duration_for);

// Results will vary based on system performance
?>

Conclusion

PHP offers flexible tools for handling dates and times. While older functions like date(), time(), mktime(), and strtotime() exist, the modern object-oriented approach using DateTime, DateTimeImmutable, DateTimeZone, DateInterval, and DateTime::createFromFormat() is generally preferred for its clarity, robustness, and explicit timezone handling. Truly, mastering these will make working with dates and times in your PHP applications much smoother.

Robin Metcalfe

About the Author: Robin Metcalfe

Robin is a freelance web strategist and developer based in Edinburgh, with over 15 years of experience helping businesses build effective and engaging online platforms using technologies like Laravel and WordPress.

Get in Touch