kevinabraham
kevinabraham

Reputation: 1437

How to parse date string to dateTime in php?

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

Upvotes: 0

Views: 1732

Answers (2)

niiwig
niiwig

Reputation: 160

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');

Upvotes: 6

Blackbam
Blackbam

Reputation: 19366

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.

Upvotes: 2

Related Questions