PHP date function
Purpose:
* The date() function in PHP is used to format a timestamp into a human-readable date and time string.
* It takes a timestamp as input and returns a formatted string based on the specified format.
Syntax:
string date ( string $format [, int $timestamp ] )
* $format: A string specifying the desired output format. It consists of various characters that represent different date and time elements.
* $timestamp: An optional integer representing the timestamp. If omitted, the current time is used.
Format Characters:
* Day:
* d: Day of the month (01-31)
* D: Three-letter day name (Mon, Tue, Wed, …)
* l: Full day name (Monday, Tuesday, Wednesday, …)
* Month:
* m: Month (01-12)
* F: Full month name (January, February, March, …)
* M: Three-letter month name (Jan, Feb, Mar, …)
* Year:
* Y: Four-digit year (2023)
* y: Two-digit year (23)
* Time:
* a: AM or PM
* A: AM or PM (in uppercase)
* h: Hour (12-hour format, 01-12)
* H: Hour (24-hour format, 00-23)
* i: Minutes (00-59)
* s: Seconds (00-59)
* Other:
* t: Number of days in the current month
* L: Whether it’s a leap year (1 if leap year, 0 if not)
* w: Day of the week (0-6, Sunday is 0)
* z: Day of the year (0-365)
Examples:
// Current date and time in various formats
echo date(“Y-m-d H:i:s”); // 2023-12-31 23:59:59
echo date(“D, M j, Y”); // Sun, Dec 31, 2023
echo date(“l, F j, Y”); // Sunday, December 31, 2023
echo date(“h:i:s A”); // 11:59:59 PM
echo date(“H:i:s”); // 23:59:59
// Custom time zone
date_default_timezone_set(‘America/Los_Angeles’);
echo date(“Y-m-d H:i:s”); // 2023-12-31 15:59:59 (Pacific Time)
// Using a timestamp
$timestamp = strtotime(“2024-01-01”);
echo date(“Y-m-d”, $timestamp); // 2024-01-01
Key Points:
* The date() function is versatile for formatting timestamps in various ways.
* The format string is crucial for customizing the output.
* You can use the strtotime() function to convert human-readable date/time strings into timestamps.
* The date_default_timezone_set() function allows you to set the default time zone for date/time calculations.