2

I have a multilingual site. English and Dutch are the languages. I need to display date format in Dutch, ie I need to display a timestamp in Dutch(nl), as 16 oktober 2017. Tried the below code and format_date(), but didn't do the trick.

$date = $node->getCreatedTime(); 
\Drupal::service('date.formatter')->format($date, 'custom', 'd F Y', $timezone = NULL, $langcode = 'nl'); //not working for me

format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = 'nl');

Above code returned date in "en" language. Am I missing something here.. Thanks..

2
  • Do you really need to do it with code? You can translate date formats in /admin/config/regional/date-time and use translated date formats in any view mode / display setting
    – Hudri
    Commented May 8, 2018 at 13:24
  • You need write something like: $date = $node->getCreatedTime(); \Drupal::service('date.formatter')->format($date, 'custom', 'd F Y', NULL, 'nl');
    – chalo
    Commented Dec 19, 2018 at 17:42

3 Answers 3

5

You need write something like:

$date = $node->getCreatedTime(); 
\Drupal::service('date.formatter')->format($date, 'custom', 'd F Y', NULL, 'nl');
4

The Drupal way of handling and translating Dates is through Configuration > Regional and language > Date and time formats, as Hudri mentioned in his comment.

The same date and time Pattern between languages

What you should do depends on what pattern you want your date to be in English, if it should also be 'd F Y' as in Dutch. If yes, then you should edit the relevant Date format through the interface. Content types use Medium as default for the “Submitted by” so edit that to keep things simple.

I expect you'll have the date and time related terms already translated into Dutch, so you'll get oktober and not October on the Dutch side.

Different date and time Pattern between languages

If you want the Pattern of the same Date format to be different between laguages, for example you want English to be “10/16/2017” with Dutch “16 oktober 2017” you need to translate the Date format Pattern.

What is important to mention is that you need to have the Configuration Translation module enabled to be able to translate Date format Patterns. This will add the Translate link to the Operations button drop-down:

translate_Dateandtime

This enables you to have a different Pattern for different Languages under the same Date format.

Don't forget to Flush cache if you don't see the changes on existing content!

Code manipulation

The format_date() is Depricated, more info: Date formats API changes, public function DateFormatter::format.

-1

You dont need custom code for it, every string can be translated via the translation interface.

Check this answer https://drupal.stackexchange.com/a/139407/3776

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.