Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 434
moh_abk Avatar asked Jan 24 '16 01:01

moh_abk


People also ask

How do you convert DateTime to date in Carbon?

$date = Carbon\Carbon::createFromFormat('d/m/Y', '11/06/1990');

What is Carbon :: now ()?

Carbon::now returns the current date and time and Carbon:today returns the current date.

How do you find the Carbon date?

Simply I can format PHP date such as: $current_date_time = new DateTime("now"); $user_current_date = $current_date_time->format("Y-m-d"); to get toDay date.


1 Answers

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.

like image 63
Bogdan Avatar answered Sep 17 '22 18:09

Bogdan