3

I want to parse the following string to a DateTime() Object in PHP:

2017-03-03T09:06:41.187

I try to do this as follows:

$stateCreatedOn = DateTime::createFromFormat('Y-m-dTH:i:s.u','2017-03-03T09:06:41.187');
var_dump($stateCreatedOn); // -> Returns false

However, parsing doesn´t work and the variable is always set to false. Anybody an idea what´s wrong with my date format specification?

Thanks a lot in advance!

3 Answers 3

7
$datetime = DateTime::createFromFormat('Y-m-d\TH:i:s+', '2017-03-03T09:06:41.187');
print_r($datetime);

prints:

DateTime Object
(
    [date] => 2017-03-03 09:06:41.000000
    [timezone_type] => 3
    [timezone] => Europe/Helsinki
)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, works great - the escape \ was missing. To also get microseconds: $datetime = DateTime::createFromFormat('Y-m-d\TH:i:s.u', '2017-03-03T09:06:41.187');
1

Use strtotime() function

echo strtotime('2017-03-03T09:06:41.187'); // result will be something like 1488517601

1 Comment

strtotime() is easiest way to deal with date formatting.
0

$stateCreatedOn = DateTime::createFromFormat('Y-m-d H:i:s.u','2017-03-03 09:06:41.187'); var_dump($stateCreatedOn);

Result : object(DateTime)#1 (3) { ["date"]=> string(26) "2017-03-03 09:06:41.187000" ["timezone_type"]=> int(3) ["timezone"]=> string(13) "Europe/Berlin" }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.