根据我的经验,很多问题都归结为服务器上的区域设置。
PHP 可能会将 dd/mm/yyyy 识别为 mm/dd/yyyy 并且如果日期部分无效,则可以进行匹配。为了让 PHP 正确验证日期为 dd/mm/yyyy,请将 / 换成 - (dd-mm-yyyy) when
$launch_date = $_POST['launch_date'];
$launch_date = str_replace("/", "-", $launch_date);
$launch_date = strtotime($launch_date);
这只是一个快速破解,看看是否是这种情况。如果没有,那么我建议至少在途中放入 var_dumps 以检查日期的格式是否正确。
另一种方法是使用 date_create_from_format (http://php.net/manual/en/datetime.createfromformat.php) 解析日期以及要解析的格式。
$launch_date = date_create_from_format('d/m/Y', $launch_date );
我认为在 Windows PHP 上没有实现......所以如果你有麻烦,这里有一个功能实现
if (!function_exists('date_parse_from_format')) {
function date_parse_from_format($format, $date) {
$returnArray = array('hour' => 0, 'minute' => 0, 'second' => 0,
'month' => 0, 'day' => 0, 'year' => 0);
$dateArray = array();
// array of valid date codes with keys for the return array as the values
$validDateTimeCode = array('Y' => 'year', 'y' => 'year',
'm' => 'month', 'n' => 'month',
'd' => 'day', 'j' => 'day',
'H' => 'hour', 'G' => 'hour',
'i' => 'minute', 's' => 'second');
/* create an array of valid keys for the return array
* in the order that they appear in $format
*/
for ($i = 0; $i <= strlen($format) - 1; $i++) {
$char = substr($format, $i, 1);
if (array_key_exists($char, $validDateTimeCode)) {
$dateArray[$validDateTimeCode[$char]] = '';
}
}
// create array of reg ex things for each date part
$regExArray = array('.' => '\.', // escape the period
// parse d first so we dont mangle the reg ex
// day
'd' => '(\d{2})',
// year
'Y' => '(\d{4})',
'y' => '(\d{2})',
// month
'm' => '(\d{2})',
'n' => '(\d{1,2})',
// day
'j' => '(\d{1,2})',
// hour
'H' => '(\d{2})',
'G' => '(\d{1,2})',
// minutes
'i' => '(\d{2})',
// seconds
's' => '(\d{2})');
// create a full reg ex string to parse the date with
$regEx = str_replace(array_keys($regExArray), array_values($regExArray), $format);
// Parse the date
preg_match("#$regEx#", $date, $matches);
// some checks...
if (!is_array($matches) ||
$matches[0] != $date ||
sizeof($dateArray) != (sizeof($matches) - 1)) {
return $returnArray;
}
// an iterator for the $matches array
$i = 1;
foreach ($dateArray AS $key => $value) {
$dateArray[$key] = $matches[$i++];
if (array_key_exists($key, $returnArray)) {
$returnArray[$key] = $dateArray[$key];
}
}
return $returnArray;
}
}
编辑:以防万一这被遗漏了...确保在进入数据库时将其转换为 YYYY-MM-DD:
// Whatever you do to parse date into timestamp
$launch_date_db = date("Y-m-d H:i:s", $launch_date)
更新
PHP 喜欢时间戳……所以就这样吧:
$launch_date = strtotime($row['start_date']); // convert it into timestamp
echo date('d-m-Y', $launch_date); // format timestamp