Skip to content

Instantly share code, notes, and snippets.

@curtisharvey
Created July 22, 2015 18:52
Show Gist options
  • Save curtisharvey/287b9475b1ee9566a595 to your computer and use it in GitHub Desktop.
Save curtisharvey/287b9475b1ee9566a595 to your computer and use it in GitHub Desktop.
atempt at time parsing in php
<?php
/**
* Parse various time formats into standard H:i:s format (e.g. "2:30pm" -> "14:30:00").
*
* @param string $timeString Time to parse
* @param boolean $includeSeconds Optionally include seconds, default = true
*
* @return string|null Null if unable to parse time
*/
function parseTime($timeString, $includeSeconds = true) {
$timePattern = '/^\s*(?<hour>[01]?[0-9]|2[0-3])(?::(?<min>[0-5][0-9]))?(?::(?<sec>[0-5][0-9]))?\s*(?<meridiem>[ap](?:\.?m\.?)?)?\s*$/i';
if (preg_match($timePattern, $timeString, $matches) === 1) {
$hour = (int) $matches['hour'];
$min = isset($matches['min']) ? (int) $matches['min'] : 0;
if ($hour < 12 && isset($matches['meridiem']) && ($matches['meridiem'][0] === 'p' || $matches['meridiem'][0] === 'P')) {
$hour += 12;
}
$str = str_pad($hour, 2, '0', STR_PAD_LEFT) . ':' . str_pad($min, 2, '0', STR_PAD_LEFT);
if ($includeSeconds) {
$sec = isset($matches['sec']) ? (int) $matches['sec'] : 0;
$str .= ':' . str_pad($sec, 2, '0', STR_PAD_LEFT);
}
return $str;
}
return null;
}
/**
* Convert time string to minutes since midnight.
*
* @param string $timeString Time to parse
* @param boolean $includeSeconds Optionally include seconds and return as float, default = false
*
* @return int|float|null Null if unable to parse time
*/
function timeToMinutes($timeString, $includeSeconds = false) {
$time = parseTime($timeString, $includeSeconds);
if (isset($time)) {
$parts = explode(':', $time);
return ($parts[0] * 60) + $parts[1] + ($includeSeconds ? ($parts[2] / 60) : 0);
}
return null;
}
assert('null === timeToMinutes("foo")');
assert('90 === timeToMinutes("01:30")');
assert('90 === timeToMinutes("1:30a")');
assert('90 === timeToMinutes("1:30 am")');
assert('90 === timeToMinutes("1:30 AM")');
assert('120 === timeToMinutes("2")');
assert('120 === timeToMinutes("2a")');
assert('840 === timeToMinutes("2p")');
assert('870 === timeToMinutes("14:30")');
assert('870 === timeToMinutes("2:30p")');
assert('870 === timeToMinutes("2:30 p.m.")');
assert('870.25 === timeToMinutes("2:30:15p", true)');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment