From procedural functions like `date()` to modern `DateTime` objects, this guide covers everything you need to know.
Result will appear here...
🔥 Popular: 1,200+ developers used this tool in the last 24 hours
Unlike JavaScript, PHP traditionally works with Unix timestamps in **seconds**. The core functions and the modern `DateTime` class are all built around this standard, making interoperability with systems like Linux and databases straightforward.
For simple tasks, PHP's classic functions are quick and effective, though they are less flexible than the object-oriented approach.
<?php
// Get the current Unix timestamp (in seconds)$currentTimestamp = time();
echo $currentTimestamp;
?>
<?php
$timestamp = 1678886400;
// Format the timestamp into a readable date string
// 'Y-m-d H:i:s' is a common format
$readableDate = date('Y-m-d H:i:s', $timestamp);
echo $readableDate;
?>
<?php
$dateString = '2024-10-12 10:30:00';
// Convert a date string into a Unix timestamp
$timestamp = strtotime($dateString);
echo $timestamp;
?>
Since PHP 5.2, the `DateTime` and `DateTimeImmutable` classes have provided a much more powerful, precise, and readable way to work with dates and times. `DateTimeImmutable` is generally preferred as it prevents accidental modification of the date object.
<?php
$timestamp = 1678886400;
// Create a DateTimeImmutable object from a timestamp
// The '@' symbol is crucial to signify a Unix timestamp
$date = new DateTimeImmutable('@' . $timestamp);
// Use the format() method for output
echo $date->format('Y-m-d H:i:s');
?>
<?php
// Create a date object from a string
$date = new DateTimeImmutable('2024-10-12 10:30:00');
// Get the Unix timestamp from the object
$timestamp = $date->getTimestamp();
echo $timestamp;
?>
The `DateTime` objects make timezone handling explicit and easy. You can specify the timezone on creation or convert between them.
<?php
$timestamp = 1678886400; // This is always UTC
// Create a date object in UTC
$utcDate = new DateTimeImmutable('@' . $timestamp, new DateTimeZone('UTC'));
echo 'UTC Time: ' . $utcDate->format('Y-m-d H:i:s') . "\n";
// Convert it to another timezone, e.g., 'America/New_York'
$nyDate = $utcDate->setTimezone(new DateTimeZone('America/New_York'));
echo 'New York Time: ' . $nyDate->format('Y-m-d H:i:s') . "\n";
?>