Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
521 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...