My database stores two dates in the mysql DateTime format YYYY-MM-DD HH:MM:SS
. When I get this data (with other strings etc), I want to convert it to another format, maybe DD.MM.YYYY HH:MM:SS
and display it on my view in a table cell. My database dates are called date_begin
and date_end
.
Better, when I get this dates from database, convert it to DD.MM.YYYY
format, separate the date and the time, store the time in a custom string ("HH1:MM1 - HH2:MM2") and bring both on my view.
How can I achieve this? I found some examples to convert on the view, not in the controller, but I think this is not good for MVC.
You can always use Carbon's ->format('m/d/Y'); to change format. Or you can just use selectRaw to build your queries. Save this answer.
We change the date format from one format to another. For example - we have stored date in MM-DD-YYYY format in a variable, and we want to change it to DD-MM-YYYY format. We can achieve this conversion by using strtotime() and date() function. These are the built-in functions of PHP.
MySQL uses yyyy-mm-dd format for storing a date value. This format is fixed and it is not possible to change it. For example, you may prefer to use mm-dd-yyyy format but you can't. Instead, you follow the standard date format and use the DATE_FORMAT function to format the date the way you want.
Not sure where you've gotten the impression that "formatting the date in the view is not good for MVC", because that's not a problem whatsoever.
If you're using Eloquent Models you can do it very easily:
1. Add the columns to the $dates
property in your model class:
protected $dates = ['date_begin', 'date_end'];
This will ensure that the values get mutated to Carbon instances.
2. In your view files you can use the format
method that Carbon offers like so:
<!-- To use only the date with the given format -->
{{ $item->date_begin->format('Y.m.d') }}
<!-- To use only the time with the given format -->
{{ $item->date_begin->format('H:i:s') }}
<!-- To use both date and time with the given format -->
{{ $item->date_begin->format('Y.m.d H:i:s') }}
There's no need to split the value in time and date, just show what you want from the DateTime value using whatever format you want.
If you're not using Eloquent models, then you can manually use Carbon to format your value like so:
{{ Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $item->date_begin)->format('Y.m.d') }}
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