Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Carbon, how to get the translated day name by it's number?

Tags:

php

php-carbon

With Carbon, How to get the translated day name by providing it's number? (in the current locale)

giving that I have day number 1, I want to get Monday in english, Lunes in spanish, Montag in german and so on.

and only by using Carbon, I don't want to use kind of arrays of translated days.

I tried the Carbon::getDays() method which returns the array of day names, but Unfortunately, only in english.


2 Answers

If getting the day name is your only concern, you can do this with an array.

$weekdays = Carbon::getDays();

However, if you need a way to get the name for a locale there's 2 ways to go about it.

  1. Use translation strings (in resources/lang folder. Need to be manually added)
  2. Use Carbon:
Carbon::create($weekdays[$day])->locale($locale)->dayName;
// Carbon::create($weekdays[1])->locale('fr_FR')->dayName outputs 'lundi'
// Carbon::create($weekdays[1])->locale('es_ES')->dayName outputs 'lunes'
// Carbon::create($weekdays[1])->locale('en_US')->dayName outputs 'monday'

Alternatively, find a year that starts with a monday and you can avoid making a week days array. However, be sure to comment why you chose that specific year.

like image 72
IGP Avatar answered Sep 19 '25 03:09

IGP


It's not pretty - but this works:

Carbon::now()->year(2018)->dayOfYear(1)->locale('de')->dayName

EDIT:

Carbon::now()->year(2019)->dayOfYear(0)->locale('de')->dayName

like image 24
rareclass Avatar answered Sep 19 '25 04:09

rareclass