我将 startDate end 和 endDate 作为获取请求参数传递给方法, 在这里它们被解析为:
$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 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并不代表同一个Date
我可以从这些字符串中创建一个有效的日期时间吗?
更新:
我尝试使用createFromFormat
喜欢
$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)开始为日期创建一个新的日期
我只是不明白。
如有任何帮助,请提前致谢!
最佳答案
您输入的日期时间字符串 Wed Jan 12 2011 00:00:00 GMT 0100 (CET)
在 DateTime()
中使用无效/标准或strtotime()
。请参阅date_parse()
函数来查看如何解析日期时间字符串:
print_r( date_parse('Wed Jan 12 2011 00:00:00 GMT 0100 (CET)') );
使用 DateTime::createFromFormat()
静态方法根据具体格式返回DateTime对象。
关于PHP DateTime,解析字符串日期失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21257536/