PHP DateTime,解析字符串日期失败



im将起点末端作为get request参数传递给方法,在这里,他们被解析了:

$startDate=$request->query->get('start');
$endDate=$request->query->get('end');
$logger->info('startdate is :'.$startDate.', endDate is : '.$endDate.'');
$start=new DateTime($startDate);
$end=new DateTime($endDate); 

当我记录这两个参数时,它们可能是

startdate is: Wed Jan 12 2011 00:00:00 GMT 0100 (CET)
startDate is: Sat Jan 12 2013 00:00:00 GMT 0100 (CET)

到目前为止还不错,但是如果我从上方的字符串中记录了DateTime的启动,则返回

DateTime Object ( [date] => 0100-01-12 00:00:00 [timezone_type] => 2 [timezone] => GMT ) 
DateTime Object ( [date] => 0100-01-15 00:00:00 [timezone_type] => 2 [timezone] => GMT )

您可以看到,DateTime不表示同一日期

我可以从这些字符串中制作有效的日期时间吗?

更新:

我尝试使用create fromformat

喜欢

    $startDate=$request->query->get('start');
    $endDate=$request->query->get('end');
    $start=new DateTime::createFromFormat('D M d Y h:i:s e+O (T)',$startDate);
    $end=new DateTime::createFromFormat('D M d Y h:i:s e+O (T)',$endDate);   

但这导致例外:

FatalErrorException: Parse: syntax error, unexpected 'createFromFormat' (T_STRING), expecting variable (T_VARIABLE) or '$' in 

我也尝试了:

    $start=new DateTime(DateTime::createFromFormat('D M d Y h:i:s e+O (T)',$startDate));
    $end=new DateTime(DateTime::createFromFormat('D M d Y h:i:s e+O (T)',$endDate));   

,但这可以创建约会的日期(2014-01-21 12:28:57)

我只是不正确。

提供任何帮助,请提前!

您的输入dateTime字符串Wed Jan 12 2011 00:00:00 GMT 0100 (CET)DateTime()strtotime()中使用无效/标准。请参阅date_parse()功能,以查看如何解析DateTime字符串:

print_r( date_parse('Wed Jan 12 2011 00:00:00 GMT 0100 (CET)') );

demo

使用DateTime::createFromFormat()静态方法根据特定格式返回DateTime对象。

demo

您可能使用的日期格式是RFC2822。如php日期()页面所示:THU,2000年12月21日16:01:07 0200

您切换了一个月和日的零件,而PHP无法确定正确的零件。

最佳实践是使用Unix-Timestamp(秒后)或像ISO 8601(2004-02-12T15:19:21 00:00)这样的更好格式。

最新更新