In my Laravel application in want to display a date in Dutch format. In my config/app.php file I have my timezone and locale both set:
'timezone' => 'Europe/Amsterdam',
'locale' => 'nl',
But if I print a date in my blade file like this:
strftime('%a %e %b', strtotime($day->date))
It is still not shown in Dutch format. It works when I call the setlocale() method in the constructor of the related controller.
setlocale(LC_TIME, 'NL_nl');
How can I set this globally or define this in my configuration?
WARNING:
According to me, you are going in the wrong direction by altering the default configuration of laravel framework. As the convention says that you should not alter/edit the defaults unless your application is country specific and not for the whole world.
Read more about not changing the default configurations (forum's post is related to timezone only but applies to everything in general)
Answer
Why are you not using Carbon ?
Store the time as what laravel will do as usual, and then in the blade / controller, change the timezone and locale and display it.
Method 1:
Here's what you need to do:
Import the Carbon namespace in your controller
use Carbon\Carbon;
Then in your method:
public function yourMethodName()
{
// replace getDateAndTimeValueFromDB() with whatever
// you are using or whatever your logic is...
$dt = getDateAndTimeValueFromDB();
Carbon::setLocale('nl');
$newDt = Carbon::parse($dt)->timezone('Europe/Amsterdam');
return view('path.to.your_view_file', compact('newDt'));
}
And then in your view file, add the following wherever you want.
{{ $newDt }}
That should do it.
Method 2:
I would not suggest you to use this - the below mentioned method - because you will be mixing blade and php together which is highly not recommended as that will result in bad design of your code and your application as well, even though you will get the correct output.
You can use the Carbon
instance directly in the blade file.
Just add the following code snippet in your view.blade.file
<?php
Carbon\Carbon::setLocale('nl');
$dt = getDateAndTimeValueFromDB();
$newDt = Carbon\Carbon::parse($dt)->timezone('Europe/Amsterdam');
?>
And then echo out the converted date wherever you want in your file.
{{ $newDt }}
Hope this helps you out. Happy Coding. Cheers.
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