Current Location: Home> Latest Articles> How to Use the date() Function in PHP to Get and Format the Current Date and Time?

How to Use the date() Function in PHP to Get and Format the Current Date and Time?

gitbox 2025-08-29

<?php echo "

How to Use the `date()` Function in PHP to Get and Format the Current Date and Time?

"
; echo "

In PHP, the `date()` function is a common method for retrieving and formatting date and time. It can return the current server time or a specified timestamp formatted as a date and time string, based on the format string you provide.

"
; echo "

Basic Syntax:

"
; echo "
string date(string \$format [, int \$timestamp = time() ])
"
; echo "
  • \$format: Required, defines the format for the date/time.
  • \$timestamp: Optional, specifies the timestamp, defaults to the current time.
"
;
echo "

Common Format Characters:

"
; echo "
  • Y - Four-digit year, e.g., 2025
  • m - Two-digit month, e.g., 08
  • d - Two-digit day, e.g., 27
  • H - Hour in 24-hour format, e.g., 14
  • i - Minute, e.g., 05
  • s - Second, e.g., 09
  • l - Full weekday name, e.g., Wednesday
"
;
echo "

Example: Get the Current Date and Time:

"
; echo "
  
<?php  
echo date('Y-m-d H:i:s');  // Outputs something like 2025-08-27 14:05:09  
?>  
"
;
echo "

Formatting Example:

"
; echo "
  
<?php  
// Display full date and weekday  
echo date('l, d F Y');  // Outputs something like Wednesday, 27 August 2025  
?>  
"
;
echo "

By combining different format characters, you can customize the output, such as displaying only the date, only the time, or including the weekday. The `date()` function is an essential tool for handling time in PHP development, and it is widely used for logging, time display, and scheduling tasks.

"
; echo "

Summary:

"
; echo "

With the date() function, you can easily retrieve the current date and time and customize the output with a format string. If you need to use a specific timezone, remember to set date_default_timezone_set() before calling date().

"
; ?> <?php // End of unrelated content echo "