PHP date and time: date(), localtime(), mktime(), time(), and microtime()

In PHP, date() formats a timestamp and localtime() returns its calendar components as an array. mktime() converts local date and time fields to a Unix timestamp. time() returns the current time in integer seconds and microtime(true) returns seconds with a fractional part.

Understand Unix timestamps and run the examples

A Unix timestamp is a count of seconds from 1970-01-01 00:00:00 Coordinated Universal Time (UTC). The number does not include a time-zone name. To display Seoul time, choose a display zone instead of adding nine hours. date_default_timezone_set() sets the script’s default time zone without changing the operating system clock. PHP Manual · date_default_timezone_set()

With PHP 8.x, save each PHP block as a UTF-8 file with the indicated name. Open a terminal in the directory and run the following command for the first file. Change the filename for the remaining examples.

php date-demo.php

Format one instant in two time zones with date()

Save this example as date-demo.php. The first and third lines display 1704034800 in Seoul and UTC. The date changes while the instant stays the same. The second line uses a different format for Seoul. m is month and i is minute. If the timestamp is omitted, date() uses the current time. It accepts integer seconds, so u always returns 000000. PHP Manual · date()

<?php
declare(strict_types=1);
date_default_timezone_set('Asia/Seoul');
$timestamp = 1704034800;
echo date('Y-m-d H:i:s P', $timestamp), PHP_EOL;
echo date('d/m/Y H:i', $timestamp), PHP_EOL;
date_default_timezone_set('UTC');
echo date('Y-m-d H:i:s P', $timestamp), PHP_EOL;
date_default_timezone_set('Asia/Seoul');
2024-01-01 00:00:00 +09:00
01/01/2024 00:00
2023-12-31 15:00:00 +00:00

Read the month and year returned by localtime()

In localtime-demo.php, run localtime(1704034800, true). The second parameter gives named keys with true and numeric indexes with the default false. Add 1 to tm_mon and 1900 to tm_year to read the final date, 2024-01-01. Local time here follows PHP’s configured zone. PHP Manual · localtime()

<?php
declare(strict_types=1);
date_default_timezone_set('Asia/Seoul');
$parts = localtime(1704034800, true);
print_r($parts);
printf("Reconstructed date: %04d-%02d-%02d\n",
    $parts['tm_year'] + 1900,
    $parts['tm_mon'] + 1,
    $parts['tm_mday']);
Key Meaning Sample value
tm_sec / tm_min / tm_hour Second / minute / hour 0 / 0 / 0
tm_mday Day of the month 1
tm_mon Month starting at 0 0
tm_year Years since 1900 124
tm_wday Weekday with Sunday as 0 1, Monday
tm_yday Day of year with January 1 as 0 0
tm_isdst Positive for daylight saving, 0 for standard time, negative if unknown 0

Convert a local date with mktime() and validate it

The mktime-demo.php example supplies hour, minute, second, month, day, and year, in that order. Midnight on January 1, 2024 in Seoul is 1704034800. February 30, 2024 normalizes to March 1. Validate dates with checkdate(month, day, year) and check time ranges separately. Use === false to detect conversion failure because zero is a valid timestamp. On PHP 8, calling mktime() with no arguments raises ArgumentCountError. Use time() for the current timestamp. PHP Manual · mktime() PHP Manual · checkdate()

<?php
declare(strict_types=1);
date_default_timezone_set('Asia/Seoul');
$timestamp = mktime(0, 0, 0, 1, 1, 2024);
if ($timestamp === false) {
    throw new RuntimeException('Could not create the timestamp.');
}
echo $timestamp, PHP_EOL;
echo date('Y-m-d H:i:s', $timestamp), PHP_EOL;
$normalized = mktime(0, 0, 0, 2, 30, 2024);
if ($normalized === false) {
    throw new RuntimeException('Could not convert the date.');
}
echo 'Normalized date: ', date('Y-m-d', $normalized), PHP_EOL;
echo 'Valid input date: ', checkdate(2, 30, 2024) ? 'yes' : 'no', PHP_EOL;
1704034800
2024-01-01 00:00:00
Normalized date: 2024-03-01
Valid input date: no

Compare time() seconds with calendar days

In time-demo.php, call time() once and reuse its output for Seoul and UTC. The dates and seconds in the first three lines depend on when you run the script. Check whether another system expects seconds or milliseconds before sending a timestamp. PHP Manual · time()

<?php
declare(strict_types=1);
date_default_timezone_set('Asia/Seoul');
$now = time();
echo 'Timestamp: ', $now, PHP_EOL;
echo 'Seoul: ', date('Y-m-d H:i:s P', $now), PHP_EOL;
date_default_timezone_set('UTC');
echo 'UTC: ', date('Y-m-d H:i:s P', $now), PHP_EOL;
date_default_timezone_set('Asia/Seoul');

$ny = new DateTimeZone('America/New_York');
$localNoon = new DateTimeImmutable('2024-03-09 12:00:00', $ny);
$afterSeconds = $localNoon->setTimestamp($localNoon->getTimestamp() + 86400);
$nextDay = $localNoon->modify('+1 day');
echo 'After 86400 seconds: ', $afterSeconds->format('Y-m-d H:i:s P'), PHP_EOL;
echo 'Next calendar day: ', $nextDay->format('Y-m-d H:i:s P'), PHP_EOL;

The last two lines start from noon in New York before a daylight saving transition. Adding 86400 seconds gives 13:00 the next day, while advancing by one calendar day keeps the local time at 12:00. Use DateTimeImmutable with a named DateTimeZone for local calendar calculations such as scheduling. PHP Manual · Date and Time Arithmetic

Choose between microtime() and hrtime()

In microtime-demo.php, the default microtime() result is a string with the fractional part and integer seconds separated by a space. microtime(true) returns Unix seconds with a fractional part as a float. Separate calls can read slightly different instants. Printing more digits does not make the clock more accurate. PHP Manual · microtime()

<?php
declare(strict_types=1);
echo 'String: ', microtime(), PHP_EOL;
printf("Fractional seconds: %.6f\n", microtime(true));
$wallStart = microtime(true);
$monoStart = hrtime(true);
if ($monoStart === false) {
    throw new RuntimeException('High-resolution clock unavailable.');
}
$sum = 0;
for ($i = 1; $i <= 10000; $i++) {
    $sum += $i;
}
$monoEnd = hrtime(true);
$wallEnd = microtime(true);
if ($monoEnd === false) {
    throw new RuntimeException('High-resolution clock unavailable.');
}
echo 'Sum: ', $sum, PHP_EOL;
printf("microtime difference (s): %.9f\n", $wallEnd - $wallStart);
printf("hrtime elapsed (s): %.9f\n", ($monoEnd - $monoStart) / 1_000_000_000);

The loop always sums to 50005000. System clock adjustments can affect a difference between two microtime(true) values. To measure a duration, subtract two hrtime(true) readings from a monotonic clock and divide the nanoseconds by 1,000,000,000. Its absolute reading has no calendar meaning. PHP Manual · hrtime()