PHP Timestamp Handling – Work with Unix Timestamps 
In PHP, timestamps are like a time machine! They represent the number of seconds since January 1, 1970 (Unix Epoch). We use timestamps for date comparisons, scheduling, and much more.
Getting the Current Timestamp
Use time()
to get the current timestamp.
<?php echo "Current Timestamp: " . time(); ?>
For example, if time()
returns 1712048400
, it means **April 2, 2025, 12:00:00 AM UTC**.
Converting a Timestamp to a Readable Date
Use date()
to convert a timestamp into a formatted date.
<?php $timestamp = 1712048400; // Example timestamp echo "Formatted Date: " . date("Y-m-d H:i:s", $timestamp); ?>
This converts 1712048400
into 2025-04-02 00:00:00.
Getting a Timestamp for a Specific Date
Use strtotime()
to convert a string date into a timestamp.
<?php $timestamp = strtotime("2025-12-31"); echo "Timestamp for Dec 31, 2025: " . $timestamp; ?>
This tells us the number of seconds between January 1, 1970, and December 31, 2025.
Adding & Subtracting Time with Timestamps
We can easily modify dates using strtotime()
with relative phrases.
<?php $nextWeek = strtotime("+1 week"); echo "Next week's date: " . date("Y-m-d", $nextWeek); ?>
Other examples:
strtotime("+3 days")
→ Adds 3 daysstrtotime("-1 month")
→ Subtracts 1 month
Comparing Timestamps
Since timestamps are just numbers, comparing dates is super easy!
<?php $eventDate = strtotime("2025-05-01"); $now = time(); if ($now > $eventDate) { echo "The event has already happened!"; } else { echo "The event is in the future!
"; } ?>
This is great for countdowns, scheduling, and reminders!
Getting the Difference Between Two Dates
We can subtract timestamps to find the difference between two dates.
<?php $startDate = strtotime("2025-01-01"); $endDate = strtotime("2025-12-31"); $diff = $endDate - $startDate; $days = $diff / (60 * 60 * 24); // Convert seconds to days echo "Days between dates: $days"; ?>
This tells us there are **364 days** between **January 1, 2025**, and **December 31, 2025**.
Key Takeaways
time()
gives the current timestamp.date()
converts a timestamp to a readable format.strtotime()
converts a date string into a timestamp.- We can add, subtract, and compare timestamps easily.
Practice Time!
Try converting different dates into timestamps and calculating the number of days between them. Can you figure out how many seconds are in a year?