How to use date in PHP

PHP offers a built-in date() function that enables developers to format a date and time. This function can return the current date and time, as well as format a specified date and time. It takes a string format, which specifies how the output date should be displayed.

Syntax

date(format, timestamp)

The date function takes two parameters:

  • Format: A required parameter that specifies the format of a date and time string. It can include letters, spaces, and special characters to represent different date and time elements.
  • Timestamp: An optional parameter that specifies a Unix timestamp representing a date and time.

Parameter Values

The following table lists the most commonly used format characters that can be used in the date function. Additional format characters can be found here.

Format Character Description
d Day of the month, 2 digits with leading zeros (01-31)
F Month name, full (January-December)
Y Year, 4 digits
h Hour in 12-hour format, 2 digits with leading zeros (01-12)
i Minute, 2 digits with leading zeros (00-59)
s Second, 2 digits with leading zeros (00-59)

Usage Examples

Here are a few examples of how the date function can be used:

// Returns the current date in the format of Y-m-d
$date = date('Y-m-d');
echo $date; // Outputs something like 2022-04-12

// Returns the current date & time in the format of F d, Y h:i:s A
$datetime = date('F d, Y h:i:s A');
echo $datetime; // Outputs something like April 12, 2022 02:05:24 PM

// Returns a specified datetime in the format of h:i:s A
$timestamp = strtotime('2022-04-12 13:45:00');
$time = date('h:i:s A', $timestamp);
echo $time; // Outputs 01:45:00 PM

Technical Details

  • The default timezone will be the same as the server’s timezone, unless specified using the date_default_timezone_set() function.
  • The timestamp parameter can be left empty, in which case the current date and time will be used.
  • The maximum possible timestamp is of the year 2038 on 32-bit systems.

  Written by: Michael from Beginnrtuts.com     23-05-2023     Written in: PHP tutorials

Leave a Reply

Your email address will not be published. Required fields are marked *