timestamper.online

How to Work with Unix Timestamps in PHP

From procedural functions like `date()` to modern `DateTime` objects, this guide covers everything you need to know.

🚀 Quick Converter
Need a quick conversion without writing code? Use the tool below.
🚀 Try It Now - Convert Instantly
Paste your Unix timestamp below to see instant conversion

Result will appear here...

🔥 Popular: 1,200+ developers used this tool in the last 24 hours

Timestamps in PHP: Seconds Precision

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.

1. Procedural Functions (The Old Way)

For simple tasks, PHP's classic functions are quick and effective, though they are less flexible than the object-oriented approach.

Get Current Timestamp: `time()`

php
<?php

// Get the current Unix timestamp (in seconds)$currentTimestamp = time();
echo $currentTimestamp;

?>

Timestamp to Readable Date: `date()`

php
<?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;

?>

Readable Date to Timestamp: `strtotime()`

php
<?php

$dateString = '2024-10-12 10:30:00';

// Convert a date string into a Unix timestamp
$timestamp = strtotime($dateString);
echo $timestamp;

?>

2. The Object-Oriented Way (Recommended)

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.

Timestamp to `DateTimeImmutable` Object

php
<?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');

?>

`DateTimeImmutable` Object to Timestamp

php
<?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;

?>

3. Handling Timezones

The `DateTime` objects make timezone handling explicit and easy. You can specify the timezone on creation or convert between them.

php
<?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";

?>