Many time we need to show dates in different languages in our shop. So it is necessary that date should show in the chosen language of the customer. So In this blog we will learn how to translate dates in prestashop.
As we know locale format is languageCode_countryCode . where languageCode is in lowercase letters and countryCode is in uppercase letters.
So first we will create the locale code for the language which customer chose as his language. As we know in prestashop we always have a context object set on every page. you can use this object by two methods.
$context = Context::getContext(); Or // On every controller you can get the value of context object like this $context = $this->context;
Now get the language code of the language set in the context language. you can get the language code with the help of below code-
$contextLanguageCode = $context->language->language_code;
language_code is in the format languageCode-countryCode . So to get locale from language code, we just have to replace character hyphen(-) with underscore (_) . Lets do this with help of following lines of code-
$explodeLanguageCode = explode('-', $contextLanguageCode); $localeOfContextLanguage = $explodeLangCode[0].'_'.strtoupper($explodeLangCode[1]);
Now $localeOfContextLanguage is having the locale according to the language which customer has selected.
now lets set the locale for the environment –
setlocale(LC_ALL, $localeOfContextLanguage.'.UTF-8', $localeOfContextLanguage);
for more information on setlocale please visit the link – http://php.net/manual/en/function.setlocale.php
Lets you have a valiable names $dateToDisplay taking date value and you want to show this date variable’s value to the customer in the format – Saturday, 10 December, 2016 .
For this after doing the above process you just have to assign this date variable to the tpl file as done in the below lie of code-
$this->context->smarty->assign('dateToDisplay', $dateToDisplay);
and show the date in your tpl file . On your tpl file use the code like this-
{$dateToDisplay|date_format:"%A, %e %B}
Now this date will be shown translated according to the customer’s chosen language. So this is all you have to do for translating dates in prestashop and you can use it for many purposes on your shop.