我有两个查询,都与日期有关。
1)我有这些格式的日期,我希望在保存到数据库之前将其规范化为相同的格式:
- 7月26日星期六
- 7月28日星期一至30日星期三
- 2014年7月24日
- 9月4日
- 8月28日星期四- 9月19日星期五
- 24-07-2014
使用strtotime()
很容易算出单个的日子,但是日期范围有点棘手。
这个,例如,不工作:
$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);
因为月份只在explode()
的一边,这样做会返回:
01 January 1970
30 July 2014
2)我需要一种方法来计算日期是哪一年(它总是在未来)。类似以下语句:
if (the month in the date string has elapsed) {
the year of the date is this year + 1
}
只要每个来源为您提供一致的格式,您可以使用DateTime()
和DateTime::createFromFormat()
为您处理日期。
//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');
我将把Monday 28 - Wednesday 30 July
的处理留给你,因为你需要做更多的工作来从第二个日期得到月份,并将其应用到第一个日期。但这应该会告诉你怎么做