在PHP中解析格式不一致的日期

I have two queries, both related to dates.

1) I have dates in these formats, which I'm looking to normalise into the same format before saving into a database:

  • Saturday 26 July
  • Monday 28 - Wednesday 30 July
  • July 24th, 2014
  • Thu 4 Sep
  • Thu 28 Aug — Fri 19 Sep
  • 24-07-2014

Single days are quite easy to work out using strtotime(), but ranges of dates are a bit more tricky.

This, for example, doesn't work:

$dateString = "Monday 28 - Wednesday 30 July";

if (strpos($dateString, "-")) {
    $datePieces = explode("-", $dateString);
    $startDate = strtotime($datePieces[0]);
    $endDate = strtotime($datePieces[1]);
} else {
    $startDate = strtotime($dateString);
    $endDate = strtotime($dateString);
}

echo '<pre>';
echo date('d F Y', $startDate);
echo '<br/>';
echo date('d F Y', $endDate);

Because the month is only on one side of the explode(), doing it this way returns:

01 January 1970
30 July 2014

2) I need a way of working out what year the date is (it will always be in the future). Something along the lines of:

if (the month in the date string has elapsed) {
    the year of the date is this year + 1
}

As long as each source provides you with a consistent format you can use DateTime() and DateTime::createFromFormat() to process the dates for you.

//Saturday 26 July
$date = DateTime::createFromFormat('l j F', 'Saturday 26 July');

//July 24th, 2014
$date = new DateTime('July 24th, 2014');

//Thu 4 Sep
$date = DateTime::createFromFormat('D j M', 'Thu 4 Sep');

//Thu 28 Aug — Fri 19 Sep
list($start, $end) = explode(' - ', 'Thu 28 Aug — Fri 19 Sep');
$start = DateTime::createFromFormat('D j M', $start);
$end   = DateTime::createFromFormat('D j M', $end);

//24-07-2014
$date = new DateTime('24-07-2014');

I'm going to leave handling Monday 28 - Wednesday 30 July to you since you'll need to do a little more work to get the month from the second date and apply it to the first. But this should show you how to go about this.