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.
$date = Carbon\Carbon::createFromFormat('d/m/Y', '11/06/1990');
Carbon::now returns the current date and time and Carbon:today returns the current 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With