How could i create carbon object from given datetime structure? [duplicate]
Asked Answered
C

4

21

I use laravel, i need to create carbon object from the timestamp that i received.

TimeStamp : 'yy-mm-dd HH:mm'

ex. '2016-12-20 10:26'

Is this possible ?

Or Any other solution ?

Colwin answered 20/12, 2016 at 6:48 Comment(0)
D
36

Use Carbon::parse('2016-12-20 10:26');, it will return a Carbon object.

Dunaj answered 20/12, 2016 at 6:50 Comment(0)
C
15

Here is the official way from the Carbon docs:

Finally, if you find yourself inheriting a \DateTime instance from another library, fear not! You can create a Carbon instance via a friendly instance() function.

$dt = new \DateTime('first day of January 2008');   // <== instance from another API
$carbon = Carbon::instance($dt);
echo get_class($carbon);                               // 'Carbon\Carbon'
echo $carbon->toDateTimeString();                      // 2008-01-01 00:00:00

Also shown here

Collado answered 21/2, 2019 at 1:51 Comment(3)
This only works if you get a DateTime object, though. OP indicates they're getting what looks like a string.Ronel
Since DateTime was in the question title, I figured it was relevant.Collado
@farzan Then you could upvote this answer so more people consider it.Collado
H
14

You can use parse():

Carbon::parse($dateString);

Or you can use $dates property to create Carbon instance automatically for the column:

protected $dates = ['custom_date'];
Hornpipe answered 20/12, 2016 at 6:50 Comment(0)
D
10

Based on carbon doc, you can convert date string to carbon object like:
1) Carbon::parse('1975-05-21 22:23:00.123456')
2) Carbon::create($year, $month, $day, $hour, $minute, $second, $tz);

Dempsey answered 20/12, 2016 at 7:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.