moh_abk
moh_abk

Reputation: 2164

Create date - Carbon in Laravel

I'm starting to read about Carbon and can't seem to figure out how to create a carbon date.

In the docs is says you can;

Carbon::createFromDate($year, $month, $day, $tz); Carbon::createFromTime($hour, $minute, $second, $tz); Carbon::create($year, $month, $day, $hour, $minute, $second, $tz);

But what if I just recieve a date like 2016-01-23? Do I have to strip out each part and feed it to carbon before I can create a carbon date? or maybe I receive time like 11:53:20??

I'm dealing with dynamic dates and time and writing code to separate parts of time or date doesn't feel right.

Any help appreciated.

Upvotes: 37

Views: 97439

Answers (2)

Usama Yazdani
Usama Yazdani

Reputation: 11

use Carbon\Carbon;

$dateString = '2016-01-23';
$carbonDate = Carbon::parse($dateString);

echo $carbonDate; // Outputs: 2016-01-23 00:00:00

Upvotes: 1

Bogdan
Bogdan

Reputation: 44586

You can use one of two ways of creating a Carbon instance from that date string:

1. Create a new instance and pass the string to the constructor:

// From a datetime string
$datetime = new Carbon('2016-01-23 11:53:20');

// From a date string
$date = new Carbon('2016-01-23');

// From a time string
$time = new Carbon('11:53:20');

2. Use the createFromFormat method:

// From a datetime string
$datetime = Carbon::createFromFormat('Y-m-d H:i:s', '2016-01-23 11:53:20');

// From a date string
$date = Carbon::createFromFormat('Y-m-d', '2016-01-23');

// From a time string
$time = Carbon::createFromFormat('H:i:s', '11:53:20');

The Carbon class is just extending the PHP DateTime class, which means that you can use all the same methods including the same constructor parameters or the createFromFormat method.

Upvotes: 79

Related Questions