time(), DateTime, DateTimeImmutable. Working examples for every common operation — get current time, convert epoch to date, convert date to epoch, format display, parse, and handle timezones.
PHP's `time()` returns epoch seconds. `microtime(true)` gives float seconds with sub-second precision.
<?php
$now = time();
// → 1735689600
<?php
$ms = (int) (microtime(true) * 1000);
// → 1735689600123
<?php
$t = microtime(true);
// → 1735689600.123456
Use `DateTime` (mutable) or `DateTimeImmutable` (preferred for new code).
<?php
$dt = (new DateTimeImmutable())->setTimestamp(1735689600);
echo $dt->format(DATE_ATOM);
// → 2025-01-01T00:00:00+00:00
<?php
$tz = new DateTimeZone('America/New_York');
$dt = (new DateTimeImmutable())->setTimestamp(1735689600)->setTimezone($tz);
echo $dt->format('Y-m-d H:i:s e');
// → 2024-12-31 19:00:00 America/New_York
<?php
echo date("Y-m-d H:i:s", 1735689600); // local time
echo gmdate("Y-m-d H:i:s", 1735689600); // UTC
DateTime has `.getTimestamp()`. Or use `strtotime()` for quick string-to-epoch.
<?php
$dt = new DateTimeImmutable("2025-01-01 00:00:00 UTC");
$ts = $dt->getTimestamp();
// → 1735689600
<?php
$ts = strtotime("2025-01-01 00:00:00 UTC");
// → 1735689600
$ts2 = strtotime("next Monday");
$ts3 = strtotime("+1 hour");
Use `->format()` with PHP's format characters, or `DATE_ATOM` / `DATE_RFC2822` constants.
<?php
echo (new DateTimeImmutable())->format(DATE_ATOM);
// → 2025-01-01T12:34:56+00:00
<?php
echo (new DateTimeImmutable())->format(DATE_RFC2822);
// → Wed, 01 Jan 2025 12:34:56 +0000
<?php
echo (new DateTimeImmutable())->format('Y-m-d H:i:s');
Use `DateTimeImmutable::createFromFormat()` for known formats, or `new DateTimeImmutable($str)` for flexible parsing.
<?php
$dt = new DateTimeImmutable("2025-01-01T00:00:00Z");
<?php
$dt = DateTimeImmutable::createFromFormat("Y-m-d H:i:s", "2025-01-01 12:00:00");
if ($dt === false) {
// parsing failed
}
PHP date pitfalls.
<?php
// DateTime is mutable — methods like ->modify() change the original.
// DateTimeImmutable returns a new instance, which is safer.
$a = new DateTimeImmutable('2025-01-01');
$b = $a->modify('+1 day');
// $a is still 2025-01-01, $b is 2025-01-02
<?php
// PHP issues warnings if date.timezone is not set in php.ini.
// Either set it globally or call date_default_timezone_set() at runtime.
date_default_timezone_set("UTC");
<?php
// strtotime is flexible but unpredictable for ambiguous strings.
// Always test with your specific input format.
strtotime('01/02/2025'); // is this Jan 2 or Feb 1?
Need to quickly check what a specific timestamp converts to? Use the main converter — paste any value and get every format back.
Working with many timestamps at once? Try the batch converter — paste a list, get a CSV or JSON file back.