
PHP is widely used for handling date and time operations in web applications. These operations are essential for showing dynamic content, scheduling daily tasks, and managing database records.
1. Getting the Current Date and Time
You can get the current date and time using PHP’s date()
function. The following example returns a full date and time string including year, month, day, hour, minute, and second:
echo date('Y-m-d H:i:s');
Output: 2025-03-06 12:45:30
Alternatively, you can use a more readable format:
echo date('d/m/Y H:i'); // 06/03/2025 12:45
2. Formatting a Specific Date
Using date()
, you can display the date in different formats:
echo date('l, d F Y');
Output: Thursday, 06 March 2025
Common format characters:
Y
– 4-digit year (2025
)y
– 2-digit year (25
)m
– Month number (03
)d
– Day of the month (06
)l
– Full name of the day (Thursday
)F
– Full name of the month (March
)
3. Using Timestamps
A UNIX timestamp represents the number of seconds since January 1, 1970. Use time()
to get the current timestamp:
echo time();
Example Output: 1740637530
Use strtotime()
to convert a specific date to a timestamp:
echo strtotime('2025-04-15');
Output: 1744675200
Convert the timestamp back to a human-readable date:
echo date('Y-m-d H:i:s', 1744675200);
Output: 2025-04-15 00:00:00
4. Comparing Dates and Calculating Differences
You can calculate the difference between two dates using the DateTime
class:
$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
Alternatively, use strtotime()
to calculate the difference in seconds:
$diffInSeconds = strtotime('2025-03-06') - strtotime('2025-03-01');
echo $diffInSeconds / 86400 . ' days';
Output: 5 days
5. Setting Time Zones
To set the default time zone for your application:
date_default_timezone_set('Europe/Istanbul');
echo date('Y-m-d H:i:s');
To list all available time zones:
print_r(timezone_identifiers_list());
6. Calculating Future or Past Dates
Use strtotime()
to add days, weeks, or months to a date:
$nextMonth = date('Y-m-d', strtotime('+1 month'));
echo $nextMonth;
Or use the DateTime
class for more flexibility:
$date = new DateTime('2025-03-06');
$date->modify('+2 weeks');
echo $date->format('Y-m-d');
Output: 2025-03-20
Related Articles
