Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
535 views
in Technique[技术] by (71.8m points)

date - php datetime createformat parse

I'm trying to parse following string:

 Thu Oct 03 2013 07:03:41 GMT+0200 (Central Europe Standard Time)

But I'm struggling to find the corresponding format, I tried:

  $date= DateTime::createFromFormat('D M d Y H:i:s eO (*)','Thu Oct 03 2013 07:03:41 GMT+0200 (Central Europe Standard Time)');
  echo $date->format('Y-m-d');

Which results in error. Problem is, that there is no space between GMT+0200 and the brackets. Following works just fine

$date= DateTime::createFromFormat('D M d Y H:i:s e O','Thu Oct 03 2013 07:03:41 GMT +0200');
echo $date->format('Y-m-d');

But (obviously) I should be able to parse also the first example. So do you have any suggestion how the correct format should look like?

the error I get:

Fatal error: Call to a member function format() on a non-object in C:....

var_dump of $date before calling $date->format:

 boolean false
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is the format string, which should be

D M d Y H:i:s e+

I have replaced eO with just e because the input contains GMT+0200, which does not have a separator between "GMT" and the offset. I have also replaced the (*) part with +, which is the only specifier that can consume a variable amount of input (* matches one token, i.e. one word -- if there is more input afterwards the parse fails).

Note that there will still be a warning due to the use of + (use DateTime::getLastErrors to see it), but the conversion will work correctly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...