$pattern = '/^\d{4}[-](0?[1-9]|1[0-2])[-](0?[1-9]|[12]\d|3[01])' .
'(\s+(0?\d|1\d|2[0-3]):(0?\d|[1-5]\d):(0?\d|[1-5]\d))?$/';
$time = '2012-02-16 23:59:59';
if (preg_match($pattern, $time)) {
echo strtotime($time); // 1329407999
} else {
echo '格式錯誤';
}
^\d{4}:4位年份開頭[-]:分隔符連字符(0?[1-9]|1[0-2]):月份 1-12,可選前導 0(0?[1-9]|[12]\d|3[01]):日期 1-31(\s+(0?\d|1\d|2[0-3]):(0?\d|[1-5]\d):(0?\d|[1-5]\d))?:可選時間部分(時:分:秒)$:字符串結尾// 僅匹配日期
preg_match_all('/\d{4}[-\/]\d{2}[-\/]\d{2}/', $str, $dates);
// 匹配日期+時間
preg_match_all('/\d{4}[-\/]\d{2}[-\/]\d{2}\s+\d{2}:\d{2}:\d{2}/', $str, $datetimes);
$text = "嘿嘿2010/07/08 12:31:56哈哈1999-12-31 13:21:45";
// 統一提取:支持 / 或 - 分隔
preg_match_all('/\d{4}[-\/]\d{2}[-\/]\d{2}(?:\s+\d{2}:\d{2}:\d{2})?/', $text, $matches);
foreach ($matches[0] as $dt) {
// 統一分隔符為 - 便于 strtotime 解析
$dt = str_replace('/', '-', $dt);
$ts = strtotime($dt);
echo "$dt => $ts\n";
}
/* 輸出:
2010-07-08 12:31:56 => 1278563516
1999-12-31 13:21:45 => 946627305
*/
PHP date() 受 32 位系統限制,只能處理 1970-2038 年。蔡勒公式可計算任意年份星期:
function getWeekZeller($year, $month, $day) {
if ($month < 3) {
$month += 12;
$year--;
}
$c = (int)($year / 100);
$y = $year % 100;
$w = ($y + (int)($y/4) + (int)($c/4) - 2*$c + (int)(26*($month+1)/10) + $day - 1) % 7;
return ($w + 7) % 7; // 0=周日, 1=周一...
}
// 測試 2049-10-01 (建國100周年)
echo getWeekZeller(2049, 10, 1); // 5 = 星期五
$dt = DateTime::createFromFormat('Y-m-d H:i:s', '2012-02-16 23:59:59');
if ($dt) {
echo $dt->getTimestamp(); // 1329407999
echo $dt->format('l'); // Thursday
echo $dt->format('w'); // 4 (0=周日)
}
// 支持 64 位系統任意年份
$dt = new DateTime('2049-10-01');
echo $dt->format('l'); // Friday
str_replace('/', '-', ...) 統一格式DateTime 類(PHP 5.2+),跨平台、無年份限制、功能豐富strtotime 配合蔡勒公式補足