phplaravellaravel-5php-carbon

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.


Solution

  • 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.