getdate()
The getdate()
function takes one optional parameter: $timestamp
. If a timestamp is provided the function returns an associative array containing date and time values for that timestamp, otherwise it returns date and time values for the local time.
<?php //Syntax getdate(?int $timestamp = null): array
The following table lists the elements contained in the array returned by getdate()
.
Key | Possible Value |
---|---|
seconds | 0 to 59 |
minutes | 0 to 59 |
hours | 0 to 23 |
mday | 1 to 31 (Day of the month) |
wday | 0 to 6 (Day of the week) 0 for Sunday, 1 for Monday, and so on. |
mon | 1 to 12 (Month of the year) |
year | Year, 4 digits. For example 2022 |
yday | 0 to 365 (Day of the year) |
weekday | Sunday to Saturday |
month | January to December |
0 | Timestamp |
Example: Get the current local date and time
<?php $array = getdate(); print_r($array); /* Prints: Array( [seconds] => 54 [minutes] => 52 [hours] => 10 [mday] => 6 [wday] => 6 [mon] => 8 [year] => 2022 [yday] => 217 [weekday] => Saturday [month] => August [0] => 1659775974 ) */
Converting a Timestamp to Date or Time
If you have a timestamp and you want to convert it to a readable date/time form, use the getdate()
function, see the following example:
<?php $a = getdate(2009077887); echo $a['weekday'] .' '. $a['mday'] .' '. $a['month'] .' '. $a['year'] .', '. $a['hours'] .':'. $a['minutes'] .':'. $a['seconds']; # Prints: Wednesday 31 August 2033, 7:11:27
The getdate()
function returns an associative array, use date()
function if you want a string. The date()
function not only parses a timestamp it also returns a formatted date and time string as per your requirements. The following example demonstrates how the date() function format and returns the string:
<?php echo date('l d F Y, g:i:s', 2009077887); # Prints: Wednesday 31 August 2033, 7:11:27
Visit Formatting Date and Time with date() tutorial to read more about the date()
function.
Converting date or time into a timestamp
There are various ways to generate a Unix timestamp by using the time()
, mktime()
, or strtotime()
functions, see the following example:
<?php echo mktime(7,11,27,8,31,2033) . '<br>'; # Prints: 2009077887 echo strtotime('31 August 2033, 7:11:27'); # Prints: 2009077887
For more information, visit How to convert or generate timestamps tutorial.
The Date and Time Tutorials:
- PHP DateTime Class
- PHP DateTimeZone Class – times in different countries
- PHP DateInterval Class – adds or subtracts dates/times
- PHP DatePeriod Class – generates date or time ranges
- PHP Validating Age and Date of Birth
- Sunset, Sunrise, Transit, and Twilight
- Localizing Dates
- Localizing Dates with IntlDateFormatter Class