0

I have a date string in this format "2014-12-01 16:00:02,153". How do I parse this to a datetime format for mysql?

I am using laravel and Carbon. My code is Carbon::parse("2014-12-01 16:00:02,153");

but get an error that reads DateTime::__construct(): Failed to parse time string (2014-12-01 16:00:02,153) at position 20 (1): Unexpected character

2
  • 2
    the comma is the problem i believe, you should trim it and anything after that and it should work Commented Sep 25, 2018 at 11:36
  • Possible duplicate of DateTime::createFromFormat - php format issue Commented Sep 27, 2018 at 13:06

2 Answers 2

6

You could use the createFromFormat method from the DateTime object :

$dateTime = DateTime::createFromFormat('Y-m-d H:i:s,u', "2014-12-01 16:00:02,153");
echo $dateTime->format('Y-m-d H:i:s');
Sign up to request clarification or add additional context in comments.

1 Comment

Welcome. Also a great idea +1 for this!
2

PHP is confused by the time format you are handing over.

new DateTime("2014-12-01 16:00:02,153"); // fails

strtotime("2014-12-01 16:00:02,153"); // fails

This is because of the unexpected part with the comma at the end. Where are you getting this strange timestamp with comma seperated milliseconds from? It is unusual.

As you are asking for datetime which usually does not need any milliseconds you can do the following:

$timeparts = explode(",","2014-12-01 16:00:02,153");

Carbon::parse($timeparts[0]); // should work

$timeparts[1] is the milliseconds then.

If you want to be more precise you can round the milliseconds:

if(intval($timeparts[1]) >= 500) {
   // time +1 second
}

... or you treat the milliseconds seperatly if you need em. Add them to the generated timestamp later and check the docs of Carbon.

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.