The getdate()
function in PHP returns an associative array containing information about the current date and time, or the date and time specified by a Unix timestamp. The array includes various elements like the year, month, day, hour, minute, second, and more.
Syntax:
getdate(int $timestamp = time()): array
- $timestamp: This is an optional parameter. If provided, it uses the specified Unix timestamp to return the date and time. If not provided, it defaults to the current date and time.
Return Value:
An associative array with the following keys:
- "seconds": Second of the minute (0 - 59)
- "minutes": Minute of the hour (0 - 59)
- "hours": Hour of the day (0 - 23)
- "mday": Day of the month (1 - 31)
- "wday": Day of the week (0 - 6, Sunday = 0)
- "mon": Month of the year (1 - 12)
- "year": Current year (e.g., 2025)
- "yday": Day of the year (0 - 365)
- "weekday": Full textual representation of the day (e.g., "Monday")
- "month": Full textual representation of the month (e.g., "April")
Example 1: Get current date and time
<?php
$date = getdate();
print_r($date);
?>
Output:
Array
(
[seconds] => 30
[minutes] => 45
[hours] => 14
[mday] => 27
[wday] => 6
[mon] => 4
[year] => 2025
[yday] => 116
[weekday] => Saturday
[month] => April
)
Example 2: Get date for a specific Unix timestamp
<?php
$timestamp = strtotime("2025-05-15 12:30:00");
$date = getdate($timestamp);
print_r($date);
?>
Output:
Array
(
[seconds] => 0
[minutes] => 30
[hours] => 12
[mday] => 15
[wday] => 4
[mon] => 5
[year] => 2025
[yday] => 134
[weekday] => Thursday
[month] => May
)
Example 3: Format date using elements from getdate()
<?php
$date = getdate();
echo "Today is " . $date['weekday'] . ", " . $date['mday'] . " " . $date['month'] . " " . $date['year'];
?>
Output:
Today is Saturday, 27 April 2025
Use Case:
You can use getdate()
when you need to manipulate or display date and time in a more detailed or human-readable format. It helps to break down the individual components like the year, month, day, and time for further use in calculations or display.