What's the best way to localise a date on Laravel? - php

Take this example:
{{ $article->created_at->format('M') }}
It returns Nov. I need to localise this to my language, so the output should be Kas
Thought about doing the following:
{{ trans("language.{$article->created_at->format('M')}") }}
app/lang/tr/language.php -> 'nov' => 'kas'
This looks like reinventing the wheel and programmatically pretty terrible. I'm sure there are some localisation standards. Something like:
{{ $article->created_at->format('M')->localiseTo('tr_TR') }}
What's the best way to achieve this?

Using a library as Laravel-Date you will just need to set the language of the app in the Laravel app config file and use its functions to format the date as you want.
Set the language in /app/config/app.php
'locale' => 'es',
I've found this library pretty useful and clean. To use it, you can write something like the example in the library readme file. I leave the results in spanish.
echo Date::now()->format('l j F Y H:i:s'); // domingo 28 abril 2013 21:58:16
echo Date::parse('-1 day')->diffForHumans(); // 1 día atrás
This is the link to the repository:
https://github.com/jenssegers/laravel-date
To install this library you can follow the instructions detailed in the following link:
https://github.com/jenssegers/laravel-date#installation

When you retrieve a date off a model in Laravel, you get back a Carbon object:
https://github.com/briannesbitt/Carbon
If you refer to the Carbon documentation, it tells you how you can get a locale formatted Date:
Unfortunately the base class DateTime does not have any localization
support. To begin localization support a formatLocalized($format)
method has been added. The implementation makes a call to strftime
using the current instance timestamp. If you first set the current
locale with setlocale() then the string returned will be formatted in
the correct locale.
setlocale(LC_TIME, 'German');
echo $dt->formatLocalized('%A %d %B %Y'); // Donnerstag 25 Dezember 1975
setlocale(LC_TIME, '');
echo $dt->formatLocalized('%A %d %B %Y'); // Thursday 25 December 1975
So basically, just use formatLocalized('M') instead of format('M')

As of carbon version 2.30.0, you can use the translatedFormat function
$date = Carbon::parse('2021-12-08 11:35')->locale('pt-BR');
echo $date->translatedFormat('d F Y'); // 08 dezembro 2021

It is also a good idea to set locale globally for each request (eg. in filters.php) when using Carbon date instances.
App::before(function($request) {
setlocale(LC_TIME, 'sk_SK.utf8');
});
and then proceed as usual
$dt->formatLocalized('%b'); // $dt is carbon instance
See format options here and list of locales here.

In addition to the accepted answer, I was looking for a way to use this within Blade using the Carbon instance of created_at for example. The class in the accepted answer didn't seem to accept a Carbon instance as date, but rather parsed a date from a string.
I wrote a little helper function to shorten the code in the blade templates:
function localeDate($date, $format)
{
return Jenssegers\Date\Date::createFromFormat('d-m-Y H:i:s', $date->format('d-m-Y H:i:s'))->format($format);
}
Within Blade you can now use:
{{ localeDate($model->created_at, 'F') }}
Which would return the fully written name of the month in the locale set in config/app.php
If there's a better way (or I missed something in the code), please let me know. Otherwise this might be helpfull for others.

Goto your App->Config->app.php
put
'timezone' => 'Asia/Kolkata',
use simple {{$post->created_at->diffForHumans()}}

Localized (i18n) date with Laravel 8
In Laravel 8, I added a method in my Block Model:
use Illuminate\Support\Carbon;
class Block extends Model
{
public function updatedDate() {
return Carbon::parse($this->updated_at)->translatedFormat('d F Y');
}
}
In my Blade template, I want to get the latest row's update date:
{{ $blocks->last()->updatedDate() }} // prints out 25 January 2022
// PS. Carbon uses your app.locale config variable so setting locale() is optional
// return Carbon::parse($this->updated_at)->locale('en')->translatedFormat('d F Y')

I guess you should consult setlocale manpage. Though Im not sure if Laravel has any wrapper on it.

Related

Carbon date language not change on format [duplicate]

Ive read several stackoverflows about set locale. I tested locale -a in the terminal to see if my locale was in there, and it was. The following rule of code is added in the appServiceProvider:
public function boot()
{
Carbon::setLocale($this->app->getLocale());
}
The $this->app->getLocale() returns "nl"
Anyone know why Carbon still shows Sunday instead of Zondag for example?
Translating a carbon date using global localized format
Tested in: Laravel 5.8, Laravel 6, Laravel 8
In config/app.php
'locale' => 'id', // The default is 'en', but this time I want localize them to Indonesian (ID)
Then, to make locale output do something like this:
// WITHOUT LOCALE
Carbon\Carbon::parse('2019-03-01')->format('d F Y'); //Output: "01 March 2019"
now()->subMinute(5)->diffForHumans(); // Output: "5 minutes ago"
// WITH LOCALE
Carbon\Carbon::parse('2019-03-01')->translatedFormat('d F Y'); // Output: "01 Maret 2019"
now()->subMinute(5)->diffForHumans(); // Output: "5 menit yang lalu"
For more information about converting localize dates you can see on below link
https://carbon.nesbot.com/docs/#api-localization
You might want to use setLocale(LC_TIME, $this->app->getLocale()) somewhere at the start of your application.
Then if you wish to have the localized date format with local names use the formatLocalized function
Carbon::now()->formatLocalized('%d %B %Y');
See http://php.net/manual/en/function.strftime.php for parameter for formatting
Researching I have found two alternative options:
$date = Carbon::now();
$date->locale('de')->translatedFormat('d F Y');
and:
$date = Carbon::now();
$carbonDateFactory = new CarbonFactory([
'locale' => 'de_DE',
'timezone' => 'Europe/Paris',
]);
$carbonDateFactory->make($date)->isoFormat('d MMMM YYYY');
and the ISO compatible format symbols are here
I solved this by calling setLocale on multiple classes:
$locale = 'nl_NL';
\Carbon\Carbon::setLocale($locale);
\Carbon\CarbonImmutable::setLocale($locale);
\Carbon\CarbonPeriod::setLocale($locale);
\Carbon\CarbonInterval::setLocale($locale);
\Illuminate\Support\Carbon::setLocale($locale);
There's also this ServiceProvider that does the same.
In your AppServiceProvider's register function:
setlocale(LC_TIME, 'nl_NL.utf8');
Carbon::setLocale(config('app.locale'));
Then use translatedFormat() instead of format() or formatLocalized() which is deprecated.
This uses the date() patern which works like format() but translates the string using the current locale.
read more here and here.
try this : setLocale(LC_TIME, app()->getLocale());

Carbon setLocale not working Laravel

Ive read several stackoverflows about set locale. I tested locale -a in the terminal to see if my locale was in there, and it was. The following rule of code is added in the appServiceProvider:
public function boot()
{
Carbon::setLocale($this->app->getLocale());
}
The $this->app->getLocale() returns "nl"
Anyone know why Carbon still shows Sunday instead of Zondag for example?
Translating a carbon date using global localized format
Tested in: Laravel 5.8, Laravel 6, Laravel 8
In config/app.php
'locale' => 'id', // The default is 'en', but this time I want localize them to Indonesian (ID)
Then, to make locale output do something like this:
// WITHOUT LOCALE
Carbon\Carbon::parse('2019-03-01')->format('d F Y'); //Output: "01 March 2019"
now()->subMinute(5)->diffForHumans(); // Output: "5 minutes ago"
// WITH LOCALE
Carbon\Carbon::parse('2019-03-01')->translatedFormat('d F Y'); // Output: "01 Maret 2019"
now()->subMinute(5)->diffForHumans(); // Output: "5 menit yang lalu"
For more information about converting localize dates you can see on below link
https://carbon.nesbot.com/docs/#api-localization
You might want to use setLocale(LC_TIME, $this->app->getLocale()) somewhere at the start of your application.
Then if you wish to have the localized date format with local names use the formatLocalized function
Carbon::now()->formatLocalized('%d %B %Y');
See http://php.net/manual/en/function.strftime.php for parameter for formatting
Researching I have found two alternative options:
$date = Carbon::now();
$date->locale('de')->translatedFormat('d F Y');
and:
$date = Carbon::now();
$carbonDateFactory = new CarbonFactory([
'locale' => 'de_DE',
'timezone' => 'Europe/Paris',
]);
$carbonDateFactory->make($date)->isoFormat('d MMMM YYYY');
and the ISO compatible format symbols are here
I solved this by calling setLocale on multiple classes:
$locale = 'nl_NL';
\Carbon\Carbon::setLocale($locale);
\Carbon\CarbonImmutable::setLocale($locale);
\Carbon\CarbonPeriod::setLocale($locale);
\Carbon\CarbonInterval::setLocale($locale);
\Illuminate\Support\Carbon::setLocale($locale);
There's also this ServiceProvider that does the same.
In your AppServiceProvider's register function:
setlocale(LC_TIME, 'nl_NL.utf8');
Carbon::setLocale(config('app.locale'));
Then use translatedFormat() instead of format() or formatLocalized() which is deprecated.
This uses the date() patern which works like format() but translates the string using the current locale.
read more here and here.
try this : setLocale(LC_TIME, app()->getLocale());

change the date format in laravel view page [duplicate]

This question already has answers here:
Convert one date format into another in PHP
(17 answers)
Closed 12 months ago.
I want to change the date format which is fetched from database.
now I got 2016-10-01{{$user->from_date}} .I want to change the format 'd-m-y' in laravel 5.3
{{ $user->from_date->format('d/m/Y')}}
Try this:
date('d-m-Y', strtotime($user->from_date));
It will convert date into d-m-Y or whatever format you have given.
Note: This solution is a general solution that works for php and any of its frameworks. For a Laravel specific method, try the solution provided by Hamelraj.
In Laravel use Carbon its good
{{ \Carbon\Carbon::parse($user->from_date)->format('d/m/Y')}}
In your Model set:
protected $dates = ['name_field'];
after in your view :
{{ $user->from_date->format('d/m/Y') }}
works
You can check Date Mutators: https://laravel.com/docs/5.3/eloquent-mutators#date-mutators
You need set in your User model column from_date in $dates array and then you can change format in $dateFormat
The another option is also put this method to your User model:
public function getFromDateAttribute($value) {
return \Carbon\Carbon::parse($value)->format('d-m-Y');
}
and then in view if you run {{ $user->from_date }} you will be see format that you want.
There are 3 ways that you can do:
1) Using Laravel Model
$user = \App\User::find(1);
$newDateFormat = $user->created_at->format('d/m/Y');
dd($newDateFormat);
2) Using PHP strtotime
$user = \App\User::find(1);
$newDateFormat2 = date('d/m/Y', strtotime($user->created_at));
dd($newDateFormat2);
3) Using Carbon
$user = \App\User::find(1);
$newDateFormat3 = \Carbon\Carbon::parse($user->created_at)->format('d/m/Y');
dd($newDateFormat3);
Method One:
Using the strtotime() to time is the best format to change the date to the given format.
strtotime() - Parse about any English textual datetime description into a Unix timestamp
The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.
Example:
<?php
$timestamp = strtotime( "February 26, 2007" );
print date('Y-m-d', $timestamp );
?>
Output:
2007-02-26
Method Two:
date_format() - Return a new DateTime object, and then format the date:
<?php
$date=date_create("2013-03-15");
echo date_format($date,"Y/m/d H:i:s");
?>
Output:
2013/03/15 00:00:00
You can use Carbon::createFromTimestamp
BLADE
{{ \Carbon\Carbon::createFromTimestamp(strtotime($user->from_date))->format('d-m-Y')}}
I had a similar problem, I wanted to change the format, but I also wanted the flexibility of being able to change the format in the blade template engine too.
I, therefore, set my model up as the following:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
\Carbon\Carbon::setToStringFormat('d-m-Y');
class User extends Model
{
protected $dates = [
'from_date',
];
}
The setToStringFormat will set all the dates to use this format for this model.
The advantage of this for me is that I could have the format that I wanted without the mutator, because with the mutator, the attribute is returned as a string meaning that in the blade template I would have to write something like this if I wanted to change the format in the template:
{{ date('Y', strtotime($user->from_date)) }}
Which isn't very clean.
Instead, the attribute is still returned as a Carbon instance, however it is first returned in the desired format.
That means that in the template I could write the following, cleaner, code:
{{ $user->from_date->format('Y') }}
In addition to being able to reformat the Carbon instance, I can also call various Carbon methods on the attribute in the template.
There is probably an oversight to this approach; I'm going to wager it is not a good idea to specify the string format at the top of the model in case it affects other scripts. From what I have seen so far, that has not happened. It has only changed the default Carbon for that model only.
In this instance, it might be a good set the Carbon format back to what it was originally at the bottom of the model script. This is a bodged idea, but it would work for each model to have its own format.
Contrary, if you are having the same format for each model then in your AppServiceProvider instead. That would just keep the code neater and easier to maintain.
I suggest using isoFormat for better appearance on the web pages.
{{ \Carbon\Carbon::parse($blog->created_at)->isoFormat('MMM Do YYYY')}}
The result is
Jan 21st 2021
Carbon Extension
In Laravel 8 you can use the Date Casting: https://laravel.com/docs/8.x/eloquent-mutators#date-casting
In your Model just set:
protected $casts = [
'my_custom_datetime_field' => 'datetime'
];
And then in your blade template you can use the format() method:
{{ $my_custom_datetime_field->format('d. m. Y') }}
In Laravel you can add a function inside app/Helper/helper.php like
function formatDate($date = '', $format = 'Y-m-d'){
if($date == '' || $date == null)
return;
return date($format,strtotime($date));
}
And call this function on any controller like this
$start_date = formatDate($start_date,'Y-m-d');
Hope it helps!
For a more natural date format used everywhere outside of the US, with time that includes hours, minutes and seconds:
07/03/2022 19:00:00
{{ \Carbon\Carbon::parse($transaction->created_at)->format('d/m/Y H:i:s')}}
Or if you'd prefer to use a more natural 12-hour-clock-based time format like this:
07/03/2022 7:00:00 PM
{{ \Carbon\Carbon::parse($transaction->created_at)->format('d/m/Y g:i:s A')}}
Here's the full list of variables available for use in the PHP/Carbon date-time format.
Sometimes changing the date format doesn't work properly, especially in Laravel. So in that case, it's better to use:
$date1 = strtr($_REQUEST['date'], '/', '-');
echo date('Y-m-d', strtotime($date1));
Then you can avoid error like "1970-01-01"!

Zend Date giving wrong format for the CONSTANT Zend_Date::DATES

I'm having a problem getting the right date format to be returned from my function. The ZF documentation says if I use the constant "Zend_Date::DATES" or "Zend_Date::DATE_MEDIUM" it should return the date in a format 03.09.2011 for en_us locale Zend Documentation But I'm getting the date returned like this Mar 9, 2011 for both of those constants. However, if I use the "Zend_Date::DATE_SHORT" constant I get 03/09/11 which is exactly what the documentation says it should be. So why do the other two constants give me a different format...is it some catch-all default if something is wrong? I doubt this is a ZF bug because loads of people would have flooded them with the bug, so I'm sure I've just got something wrong, but I can't figure out what it might be and need a little help for anyone interested.
here's my function:
function ZEND_format_date_locale_display($str_date, $lang_LOCALE)
{
include_once $zend_lib_path . '/Zend/Date.php';
$date = new Zend_Date();
$date->set($str_date, 'yyyy-MM-dd');
$date = $date->toString(Zend_Date::DATES, $lang_LOCALE);
return $date;
}
The date comes out of the mysql database like '2011-03-09' for a March 9, 2011 date.
I call the function like this:
ZEND_format_date_locale_display('2011-03-09', 'en_us')
any help or ideas are appreciated. Thanks in advance.
Zend Documentation says that "The example output below reflects localization to Europe/GMT+1 hour (e.g. Germany, Austria, France)". So if you set your locale to e.g. 'de' you should get the expected results.
Why don't you use PHP's inbuilt functions?
You can use strtotime() to convert a date in any readable format into a UNIX timestamp, and then you can use date() to convert this timestamp into any format.
http://php.net/manual/en/function.strtotime.php
http://php.net/manual/en/function.date.php

How to change the format of timestamp in CakePHP?

In my application,I retrieve a timestamp from the table which is of the format 2009-08-18 12:09:01. I need to change this to August 18th,2009 or 18 Aug,2009. How to achieve this in CakePHP?
Are there any built in methods?
You can use the core TimeHelper to format and test dates/times.
To use it, you need to add the TimeHelper to your controller's $helpers array:
var $helpers = array('Time');
Then from the view you can format your date/time variables:
// assuming $variable['Model']['field_name'] = '2009-09-09 12:00:00':
echo $this->Time->format('F jS, Y', $variable['Model']['field_name']);
// => 'September 9th, 2009'
echo $this->Time->format('j M Y', $variable['Model']['field_name']);
// => '9 Sep 2009'
Since this method is ultimately a wrapper, use the table in the PHP documentation for the date() function to determine how to write the format string.
As of 1.3, if you reverse the order of the parameters (date first, format second) it will try to respect the date format of your locale. The above ordering will still work for backwards compatibility. More details at the bottom of this page in the migration guide.
You can use strptime to parse the string into a datetime and then strftime to format it back into the string you want.
Use the time helper as mentioned by deizel.
I would look through the file /cake/libs/view/helpers/time.php to see if there is a function there that provides the time format you are after.
The relative time functions are especially nice:
<?php echo $time->nice($dateValue); ?>
<?php echo $time->timeAgoInWords($dateValue); ?>
You can learn a great deal from reading the CakePHP source.
This should do:
<?php echo date('M js Y', strtotime($post['Post']['date'])); ?>
Here, Post is the name of the model and date is the field name.

Categories