Adarsh Sojitra
Adarsh Sojitra

Reputation: 2219

I cannot convert date and time to Carbon instance in Laravel 5.5

I am trying to create Carbon instance from different $date and $time variables. I am using following code right now.

$user->created_at = \Carbon\Carbon::parse($entry->Date." ".$entry->Time);

But I am getting this error.

In Carbon.php line 547:

DateTime::__construct(): Failed to parse time string (18/08/2017 10:49:50) at position 0 (1): Unexpected character

I also tried removing $time variable to check if it works with just $date variable or not. But In that case too, I am getting this error:

In Carbon.php line 547:

DateTime::__construct(): Failed to parse time string (18/08/2017) at position 0 (1): Unexpected character

I also tried trimming out " using trim() function to make sure that the character that Carbon cannot understand is not ". But it's giving me the same output.

How can I solve this error? I tried to find on the internet and other stack overflow questions and they suggested me to update my Carbon package and I did. But still, it's giving me the same error. I can't figure out what's wrong with the code.

UPDATE: I also tried with strtotime($entry->Date); but still, Same error!

Upvotes: 0

Views: 2473

Answers (2)

Faizan Fayaz
Faizan Fayaz

Reputation: 583

Create a timestamp of date and time . After that you can parse them using Carbon

$timestamp = Carbon::createFromTimestamp($entry->Date. $entry->Time);
$dateTime=date('d/m/Y h:i:s',$timestamp);
Carbon::parse($dateTime);

Upvotes: 0

webdevtr
webdevtr

Reputation: 480

You can use this,

Carbon::createFromFormat('d/m/Y H:i:s', $entry->Date.' '.$entry->Time);

I hope this will help

Upvotes: 3

Related Questions