PHP provides powerful functions for handling date and time operations. In this guide, we will cover formatting, time zones, timestamps, and date calculations in detail.
1. Getting the Current Date and Time
echo date("Y-m-d H:i:s");
Output: 2025-03-06 12:45:30
For a more readable format:
echo date("l, d F Y");
Output: Thursday, 06 March 2025
2. Using Timestamps
echo time();
Convert a specific date to a timestamp:
echo strtotime("2025-04-15");
Convert a timestamp to a readable date:
echo date("Y-m-d H:i:s", 1744675200);
Output: 2025-04-15 00:00:00
3. Comparing Dates and Calculating Differences
$date1 = new DateTime("2025-03-01");
$date2 = new DateTime("2025-03-06");
$diff = $date1->diff($date2);
echo "Difference: " . $diff->days . " days";
Output: Difference: 5 days
4. Setting the Time Zone
date_default_timezone_set("Europe/Istanbul");
echo date("Y-m-d H:i:s");
5. Calculating Past or Future Dates
$nextWeek = date("Y-m-d", strtotime("+1 week"));
echo $nextWeek;
Or using DateTime
:
$date = new DateTime("2025-03-06");
$date->modify("+2 weeks");
echo $date->format("Y-m-d");
Post Comment