Formatting
PHP provides extensive support for date and time formatting, allowing you to display dates and times in various formats. Here are some common examples of how to format dates and times using the DateTime class and the date() function.
Using the DateTime Class
The DateTime class provides a format() method that you can use to format dates and times. Here are some examples:
<?php
$date = new DateTime();
// Format as 'Y-m-d' (e.g., 2024-05-30)
echo $date->format('Y-m-d') . "\n";
// Format as 'd/m/Y' (e.g., 30/05/2024)
echo $date->format('d/m/Y') . "\n";
// Format as 'l, F j, Y' (e.g., Thursday, May 30, 2024)
echo $date->format('l, F j, Y') . "\n";
// Format as 'H:i:s' (e.g., 14:30:00)
echo $date->format('H:i:s') . "\n";
// Format as 'Y-m-d H:i:s' (e.g., 2024-05-30 14:30:00)
echo $date->format('Y-m-d H:i:s') . "\n";
?>
Using the date() Function
The date() function is useful for formatting the current date and time or a specific timestamp. Here are some examples:
<?php
// Current date in 'Y-m-d' format
echo date('Y-m-d') . "\n";
// Current date in 'd/m/Y' format
echo date('d/m/Y') . "\n";
// Current date and time in 'Y-m-d H:i:s' format
echo date('Y-m-d H:i:s') . "\n";
// Format a specific timestamp (e.g., 1717085400) as 'l, F j, Y'
$timestamp = 1717085400;
echo date('l, F j, Y', $timestamp) . "\n";
?>
Custom Date and Time Formats
You can create custom date and time formats using various format characters:
- Y - Four-digit year (e.g., 2024)
- y - Two-digit year (e.g., 24)
- m - Two-digit month (e.g., 05)
- n - Month without leading zeros (e.g., 5)
- d - Two-digit day of the month (e.g., 30)
- j - Day of the month without leading zeros (e.g., 30)
- H - 24-hour format of an hour with leading zeros (e.g., 14)
- G - 24-hour format of an hour without leading zeros (e.g., 14)
- i - Minutes with leading zeros (e.g., 30)
- s - Seconds with leading zeros (e.g., 00)
- l - Full textual representation of the day of the week (e.g., Thursday)
- F - Full textual representation of a month (e.g., May)
Formatting Date and Time with Time Zones
You can also include time zone information when formatting dates and times:
<?php
$date = new DateTime('now', new DateTimeZone('America/New_York'));
// Format date and time with time zone abbreviation
echo $date->format('Y-m-d H:i:s T') . "\n"; // e.g., 2024-05-30 14:30:00 EDT
// Format date and time with full time zone name
echo $date->format('Y-m-d H:i:s e') . "\n"; // e.g., 2024-05-30 14:30:00 America/New_York
// Format date and time with time zone offset
echo $date->format('Y-m-d H:i:s P') . "\n"; // e.g., 2024-05-30 14:30:00 -04:00
?>
These examples demonstrate how to format dates and times in various ways using PHP. By combining different format characters, you can customize the output to match your specific requirements. For more details on date and time formatting options, refer to the PHP documentation.