The Carbon PHP API helps deals many complex situations when working with dates, times and time zones in a Laravel application. To manipulate data form a Date function, you need to format and parse it in different forms. In the previous tutorial, we learnt how Carbon parses date in any format to a specified format by the user. Lets us now go through the process for how to convert date from d-m-y to y-m-d using Carbon in a Laravel application.
We can use the same ::createFromFormat
, and format
helper functions with Carbon API. The difference here is where to pass which date format.
So, when you have a date in the format d-m-Y and you need to change it to Y-m-d. You may pass the d-m-y format in string inside the ::createFromFormat
function alongside the date variable as shown below. Then apply the format helper function alongside the new format in string.
Carbon::createFromFormat('d/m/Y', $request->stockupdate)->format('Y-m-d')
The example above is a simple single line syntax for the date conversion from one specified format (d/m/Y) to another (Y-m-d). We can do the process in a slightly different way as well.
Take the input date, i.e in d/m/Y format as shown below. Specify the format in a php variable. Pass the input date and format to the ::createFromFormat
function. You may then use the php $date
variable with any other helper function.
$input = '11/06/1990';
$format = 'd/m/Y';
$date = Carbon\Carbon::createFromFormat($format, $input)