PHP Date & Time Functions – Work with Dates in PHP 🕰️
Ever wondered how websites display the current date, timestamps, or countdown timers? PHP provides powerful functions to handle date and time with ease!
🔹 Getting the Current Date & Time
The date() function formats and returns the current date and time.
<?php
echo "Today's date: " . date("Y-m-d"); // Format: YYYY-MM-DD
?>
Common date formats:
Y-m-d→ 2025-04-02d/m/Y→ 02/04/2025l, F j, Y→ Wednesday, April 2, 2025
🔹 Displaying the Current Time
The date() function can also show time!
<?php
echo "Current time: " . date("h:i:s A"); // Format: 12-hour format with AM/PM
?>
Time format examples:
h:i:s A→ 08:30:45 PMH:i:s→ 20:30:45 (24-hour format)
🔹 Getting a Timestamp
A timestamp is the number of seconds since **January 1, 1970** (Unix Epoch).
<?php echo "Current Timestamp: " . time(); ?>
Why use timestamps? They help in comparing dates, storing time in databases, and handling time zones.
🔹 Converting a Timestamp to a Date
We can convert timestamps into human-readable dates using date().
<?php
$timestamp = 1735670400; // Example timestamp
echo "Formatted Date: " . date("Y-m-d H:i:s", $timestamp);
?>
🔹 Adding & Subtracting Time
We can modify dates using strtotime().
<?php
echo "Tomorrow: " . date("Y-m-d", strtotime("+1 day")) . "<br>";
echo "Next Week: " . date("Y-m-d", strtotime("+1 week")) . "<br>";
echo "Last Month: " . date("Y-m-d", strtotime("-1 month")) . "<br>";
?>
This is super useful for setting expiration dates, scheduling posts, and more!
🔹 Working with Time Zones
By default, PHP uses the server’s time zone. We can change it using date_default_timezone_set().
<?php
date_default_timezone_set("America/New_York"); // Set time zone
echo "New York Time: " . date("h:i A");
?>
Some common time zones:
Asia/Kolkata→ IndiaEurope/London→ UKAmerica/New_York→ Eastern US
🎯 Key Takeaways
date()formats and displays the current date & time.time()returns the current timestamp.strtotime()is used for modifying dates.- Always set the correct
time zonefor accurate results.
📝 Practice Time!
Try setting different time zones and experiment with date formats. Can you display yesterday’s date in a custom format? 🚀