I did the following to really translate months and weekdays from any language (which is installed on the server).
I even thought that this topic will be answered for a long time, I will publish it, since it can really help some people.
Is used
setlocale (), but also reset; therefore, it cannot mess up the rest of your code.
These are the functions you can use:
weekdayToEnglish($locale,$weekday,$short)
weekdayFromEnglish($locale,$weekday,$short)
monthToEnglish( $locale,$month,$short)
monthFromEnglish($locale,$month,$short)
$ locale is the language you would use in setlocale () , it depends on your server, basically something like "fr_FR";
$ weekday or $ month name of the month of the week to translate
(optional) $ short if true gives a (localized) short notation (e.g. Thu instead of Thursday or Oct instead of Octobre)
Code:
function weekdayToEnglish($locale,$weekday,$short=false) { return dateElementToEnglish($locale, $weekday, $short ? "%a" : "%A", $short? "D" : "l", 'tm_wday', "Sunday +" ," days") ; } function weekdayFromEnglish($locale,$weekday,$short=false) { return dateElementFromEnglish($locale, $weekday, $short?"%a":"%A"); } function monthToEnglish( $locale,$month,$short=false) { return dateElementToEnglish($locale, $month, $short ? "%b" : "%B", $short ? "M" : "F", 'tm_mon', "January+" ," months") ; } function monthFromEnglish($locale,$month,$short=false) { return dateElementFromEnglish($locale, $month, $short ? "%b" : "%B"); } function dateElementToEnglish($locale, $text, $strfTimeformat, $dateFormat, $dateArrayIndex, $strToTimePrefix, $strToTimeSuffix) { $saveLocale = setlocale(LC_TIME,0);setlocale(LC_TIME,$locale); $translateToNr = strptime($text, $strfTimeformat)[$dateArrayIndex] ; $readDate = strtotime($strToTimePrefix . $translateToNr . $strToTimeSuffix); $translation = date($dateFormat, $readDate); setlocale(LC_TIME,$saveLocale); return $translation; } function dateElementFromEnglish($locale,$text,$strfTimeformat) { $saveLocale = setlocale(LC_TIME,0);setlocale(LC_TIME,$locale); $translation = strftime($strfTimeformat,strtotime($text)); setlocale(LC_TIME,$saveLocale); return $translation; }
For instance:
echo weekdayToEnglish("nl_NL","vrijdag")."<br>"; echo weekdayFromEnglish("fi_FI","Monday")."<br>"; echo weekdayToEnglish("nl_NL","wo", true)."<br>"; echo weekdayFromEnglish("de_DE","Thu", true)."<br>"; echo weekdayFromEnglish("fr_FR",weekdayToEnglish("nl_NL","zaterdag"))."<br>"; echo monthFromEnglish("de_DE", "March")."<br>"; echo monthFromEnglish("fr_FR", "February", true)."<br>"; echo monthToEnglish("fr_FR", "avril")."<br>"; echo monthToEnglish("fi_FI", "joulukuu", true)."<br>";
Will yield:
Friday maanantai Wed Do samedi Mรคrz fรฉvr. April Dec