Created
October 25, 2013 10:24
-
-
Save bzarzuela/7152587 to your computer and use it in GitHub Desktop.
A date range parser in PHP that will take input like October 15-25, 2013 and return October 15, 2013 and October 25, 2013. Because it was faster to write than Google for it.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
A class that takes September 15 - 30, 2013 input and converts it into two dates. | |
Also supports September 15 to 30, 2013. | |
*/ | |
class DateRangeParser | |
{ | |
public function splitMonth($range) | |
{ | |
$range = trim($range); | |
$parts = explode(' ', $range); | |
if (count($parts) < 3) { | |
throw new Exception("The number of parts extracted is less than 3."); | |
} | |
// First and last parts should be our month and year | |
$month = array_splice($parts, 0, 1)[0]; | |
$year = array_splice($parts, -1, 1)[0]; | |
// First numeric | |
$days = []; | |
foreach ($parts as $part) { | |
$day = preg_replace('/[^0-9]/', '', $part); | |
if (is_numeric($day)) { | |
$days[] = $day; | |
} | |
} | |
if (count($days) != 2) { | |
throw new Exception("Input does not have 2 days"); | |
} | |
return [ | |
'start' => date('Y-m-d', strtotime($month . ' ' . $days[0] . ', ' . $year)), | |
'end' => date('Y-m-d', strtotime($month . ' ' . $days[1] . ', ' . $year)), | |
]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment