PHP Date and Time Functions Explained with Examples
June 20, 2024 ⚊ 3 Min read ⚊ PHPPHP offers a variety of functions for working with dates and times. These functions allow you to:
- Get the current date and time
- Format dates and times in different ways
- Parse human-readable dates into timestamps (seconds since the Unix Epoch)
- Perform calculations on dates and times
Here are some commonly used functions and examples:
Getting the Current Date and Time
PHP’s date()
function is commonly used to get the current date and time. The function takes a format string as a parameter and returns a formatted date string.
<?php
echo date('Y-m-d H:i:s'); //Output: 2024-06-17 14:35:12
?>
Y
: Four-digit yearm
: Two-digit monthd
: Two-digit dayH
: Two-digit hour (24-hour format)i
: Two-digit minutess
: Two-digit seconds
Custom Formatting
You can customize the date and time format by using different characters in the format string.
<?php
echo date('l, F j, Y g:i A'); //Output: Monday, June 17, 2024 2:35 PM
?>
l
: Full weekday nameF
: Full month namej
: Day of the month without leading zerosY
: Four-digit yearg
: Hour (12-hour format) without leading zerosA
: Uppercase AM/PM
Working with Timestamps
The time()
function returns the current Unix timestamp, the number of seconds since January 1, 1970 (UTC).
<?php
echo time(); //Output: 1718644512
?>
To convert a timestamp into a readable date, use the date()
function.
<?php
$timestamp = time();
echo date('Y-m-d H:i:s', $timestamp); //Output: 2024-06-17 13:45:33
?>
Creating Dates with mktime()
The mktime()
function allows you to create a Unix timestamp for a specific date and time.
<?php
$timestamp = mktime(14, 30, 0, 6, 17, 2024);
echo date('Y-m-d H:i:s', $timestamp); //Output: 2024-06-17 14:30:00
?>
Using strtotime()
The strtotime()
function parses an English textual datetime description into a Unix timestamp.
<?php
$timestamp = strtotime('next Monday');
echo date('Y-m-d H:i:s', $timestamp); //Output: 2024-06-24 00:00:00
?>
Formatting Date and Time with DateTime
Class
The DateTime
class provides a more flexible and object-oriented way to work with dates and times.
<?php
$date = new DateTime();
echo $date->format('Y-m-d H:i:s'); //Output: 2024-06-17 14:35:12
?>
Modifying Dates
You can modify dates easily with the DateTime
class.
<?php
$date = new DateTime('2024-06-17');
$date->modify('+1 day');
echo $date->format('Y-m-d'); //Output: 2024-06-18
?>
Additional Functions:
date_add()
: Adds a specified interval (e.g., 1 day, 1 month) to a DateTime object.date_diff()
: Calculates the difference between two DateTime objects.gmdate()
: Similar todate()
but uses GMT (Greenwich Mean Time).checkdate()
: Validates a Gregorian calendar date.