由于您不知道日期的格式,因此您应该使用date_parse
date_parse — 返回具有给定日期详细信息的关联数组
例子
print_r(date_parse("23/23/23 00:14:38"));
输出
Array
(
[year] => 2023
[month] => 3 <------------------- Attempts to correct month
[day] => 23
[hour] => 0
[minute] => 14
[second] => 38
[fraction] => 0
[warning_count] => 0
[warnings] => Array
(
)
[error_count] => 1
[errors] => Array
(
[0] => Unexpected character <----- add errors found
)
[is_localtime] =>
)
简单类
$date = "23/3/2013 00:14:38";
if (DateTimeParse::createFromString($date) !== false) {
// "valid" date
}
使用的类
class DateTimeParse {
public static function createFromString($string) {
$date = date_parse(str_replace("/", "-", $string));
if ($date['error_count'] > 0)
return false;
$date = sprintf("%d-%d-%d %d:%d:%d", $date['year'], $date['month'], $date['day'], $date['hour'], $date['minute'], $date['second']);
return \DateTime::createFromFormat("Y-m-d g:i:s", $date);
}
}