Parse datetime and timestamp
Two functions in PHP allow us to parse datetime and timestamp.
Datetime parsing
extract(date_parse($datetime));
We automatically get $year
, $month
, $day
, $hour
, $minute
, $second
as local integer variables.
We also get a few more as described in the table below.
And we get a more descriptive date_parse
exception if its output is invalid.
Timestamp parsing
extract(getdate($timestamp));
We automatically get $year
, $mon
, $mday
, $hours
, $minutes
, $seconds
as local integer variables.
We also get a few more as described in the table below.
And we get a more descriptive getdate
exception if its output is invalid.
Variables output
The variable names returned from these two functions are not the same, except for $year
.
date_parse() | getdate() |
---|---|
(int)$year |
(int)$year |
(int)$month |
(int)$mon |
(int)$day |
(int)$mday |
(int)$hour |
(int)$hours |
(int)$minute |
(int)$minutes |
(int)$second |
(int)$seconds |
(float)$fraction |
N/A |
(int)$warning_count |
N/A |
(array)$warnings |
N/A |
(int)$error_count |
N/A |
(array)$errors |
N/A |
(bool)$is_localtime |
N/A |
(int)$zone_type |
N/A |
(int)$zone |
N/A |
(bool)$is_dst |
N/A |
(string)$tz_abbr |
N/A |
(array)$relative |
N/A |
N/A | (int)$wday |
N/A | (int)$yday |
N/A | (string)$weekday |
N/A | (string)$month |
N/A | (int)0 (seconds since Unix Epoch) |
Encapsulate
To avoid local variable pollution, these PHP functions can be encapsulated.
function parse_datetime($datetime) {
extract(date_parse($datetime));
return compact('year', 'month', 'day', 'hour', 'minute', 'second');
}
function parse_timestamp($timestamp) {
extract(getdate($timestamp));
return [
'year' => $year,
'month' => $mon,
'day' => $mday,
'hour' => $hours,
'minute' => $minutes,
'second' => $seconds,
];
}
Automatically get $year
, $month
, $day
, $hour
, $minute
, $second
as local integer variables:
extract(parse_datetime($datetime));
extract(parse_timestamp($timestamp));