Вопрос

I am facing some weird issue with DateTime::createFromFormat()

I have an input date as

Fri May 09 2014 11:00:00 GMT 0200

Now when I apply the DateTime::createFromFormat() on it it does not seems be working.

So here what I did

$d = DateTime::createFromFormat('D M m Y H:i:s T 0200', 'Fri May 09 2014 11:00:00 GMT 0200');
echo $d->format("Y-m-d H:i:s");

The above code works well.

Now the issue is I saw that the value 0200 is changing for different input values which usually comes from a feed. And could not find a way to deal with this.

http://php.net/manual/en/datetime.createfromformat.php

In the manual it supports + , * to be added at the end but this gives error

so

$d = DateTime::createFromFormat('D M m Y H:i:s T *', 'Fri May 09 2014 11:00:00 GMT 0200');
Array 
( 
  [warning_count] => 0 
  [warnings] => Array ( ) 
  [error_count] => 1 
  [errors] => Array ( 
     [30] => Trailing data 
  ) 
)

The work around I am doing is by removing the last 4 digits and then using the formation as

$d = DateTime::createFromFormat('D M m Y H:i:s T', 'Fri May 09 2014 11:00:00 GMT');

But the question is, if there is a proper way to deal with this i.e. without having to replace the last 4 digits and use the input as it is and use the DateTime class to deal with it ?

$d = new DateTime('Fri May 09 2014 11:00:00 GMT 0200');

also produces the output as

DateTime Object 
( 
  [date] => 0200-05-15 11:00:00 
  [timezone_type] => 2 
  [timezone] => GMT 
) 

I checked these posts

Convert date string to UTC time with PHP

php datetime createformat parse

and did not help.

Это было полезно?

Решение

If you use + instead of *, it will work as desired. Thsi only works on PHP versions >=5.3.9. It still generates a warning (lord knows why, since you are explicitly allowing trailing data) but it doesn't cause the parse routine to outright fail, and at least it's just an internal warning and not an actual PHP warning.

What causes * to fail is that it allows (emphasis mine):

Random bytes until the next separator or digit

Since your trailing data is all digits, the * parsing returns immediately without consuming any characters, leaving the string pointer in a position where there are still trailing bytes on the end.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top