Needed to use this recently to create a specificity parameter for an API at work, it gives you a key/value array from an ISO date string regardless of what is actually set in the string (e.g. if you give 2011-06-07 04 you’ll get an array back as array(‘year’=>2011, ‘month’ => 6, ‘day’ => 7, ‘hour’ => 4). If you enter 2011-06-07 04:43 you’ll get: array(‘year’=>2011, ‘month’ => 6, ‘day’ => 7, ‘hour’ => 4, ‘minute’ => 43), works from just a year all the way to seconds.
/** * Gets the parts of a date that are set in an ISO date string. * * @param string $date date/time to use. * * @return array */ public static function getDateParts($date) { $matches = array(); preg_match( '/( ( ( ( ( (?<year>d{4}) (-(?<month>d{2}))? ) (-(?<day>d{2}))? ) (s?(?<hour>d{2}))? ) (:(?<minute>d{2}))? ) (:(?<second>d{2}))? )/x', $date, $matches ); $date = array_map('intval', array_intersect_key($matches, array_flip(array('year', 'month', 'day', 'hour', 'minute', 'second')))); return $date; }