Skip to content

Instantly share code, notes, and snippets.

@ebihimself
Last active March 15, 2023 08:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ebihimself/ac9b08c857065d36c1fcefb0ea8e5733 to your computer and use it in GitHub Desktop.
Save ebihimself/ac9b08c857065d36c1fcefb0ea8e5733 to your computer and use it in GitHub Desktop.
Carbon month name localization with Laravel

Carbon months localization with Laravel translation files

Localization

Translate your desired month in the app.php translation file under its localization directory.

Methods

parseDate() method is responsible to format and translate the month name. In case you need to edit the input format or the returned format this method needs to be modified to meet your need.

getCurrentLocalizaedDate() method is just a test method to show the output.

<?php
// This is the lang file that you place months translation in
return [
'months' => [
1 => 'January',
2 => 'February',
3 => 'March',
4 => 'April',
5 => 'May',
6 => 'June',
7 => 'July',
8 => 'August',
9 => 'September',
10 => 'October',
11 => 'November',
12 => 'December',
]
]
<?php
// namespace and import statements
class SomeController extends Controller
{
public function getCurrentLocalizaedDate(){
$now = Carbon::now()->format('Y_n');
return $this->parseDate($now); // will return the current date in a format like January 2021
}
/**
* Parse date from "Y_m" format to "{Month Name} {Year}" format.
* @param $yearMonth
* @return string
*/
private function parseDate($yearMonth)
{
list($year, $month) = explode("_", $yearMonth);
$month = trans("app.months.{$month}");
return "{$month} {$year}";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment