Local time format in Carbon

For those who don't have time to keep up with all the innovations that appear in the beautiful Carbon library, we will share the most painful moment that pisses off the developers, namely the display of the time in localized form, such as December 9, 2021.

A developer who doesn't particularly follow innovations in both PHP and Carbon can suggest an option:

$current_russian_time = Carbon::now()->locale('ru')->format('j F Y г.');

However, I can assure you that you will get something like this: December 9, 2021. The thing is, Carbon developers changed their approach to the concept of localization by switching to ISO formats. To get a localized view of date/time/day of the week, you need to use this code:

Carbon::setLocale('ru');
$current_russian_time = Carbon::now()->isoFormat('D MMMM Y г.');

This gives us the result we want: December 9, 2021.


Using Carbon::setLocale('ru'); allows you to use external keys to pass the current locale once for all subsequent timestamps. Otherwise, you would have to write constantly: Carbon::now()->locale('ru')->isoFormat('D MMMM Y y');

The introduction of isoFormat in Carbon 2.x made it possible to do interesting wonders with date and time, such as this:


$date = Carbon::parse('2018-03-16')->locale('uk');
echo $date->getTranslatedDayName('[в] dddd'); // п’ятницю
// By providing a context, we're saying translate day name like in a format such as [в] dddd
// So the context itself has to be translated first consistently.
echo "\n";
echo $date->getTranslatedDayName('[наступної] dddd'); // п’ятниці
echo "\n";
echo $date->getTranslatedDayName('dddd, MMM'); // п’ятниця
echo "\n";
// The same goes for short/minified variants:
echo $date->getTranslatedShortDayName('[наступної] dd'); // пт
echo "\n";
echo $date->getTranslatedMinDayName('[наступної] ddd'); // пт
echo "\n";

// And the same goes for months
$date->locale('ru');
echo $date->getTranslatedMonthName('Do MMMM'); // марта
echo "\n";
echo $date->getTranslatedMonthName('MMMM YYYY'); // март
echo "\n";
// Short variant
echo $date->getTranslatedShortMonthName('Do MMM'); // мар
echo "\n";
echo $date->getTranslatedShortMonthName('MMM YYYY'); // мар
echo "\n";

// And so you can force a different context to get those variants:
echo $date->isoFormat('Do MMMM'); // 16-го марта
echo "\n";
echo $date->isoFormat('MMMM YYYY'); // март 2018
echo "\n";
echo $date->isoFormat('Do MMMM', 'MMMM YYYY'); // 16-го март
echo "\n";
echo $date->isoFormat('MMMM YYYY', 'Do MMMM'); // марта 2018
echo "\n";


You can read more details about the localization features on the library's website: https://carbon.nesbot.com/docs/#api-localization

It's never too late to change your business for the better

Get start

This site uses cookies. We do not personalize you, but only make surfing the site more convenient. You can check out our Privacy Policy