6min

FAQ - How can I translate and format dates?

A demo of how you can convert dates from English to a different language

Answer:

We can use Liquid to format our "raw" date integer to a formatted date. However, this doesn't give the option to select a different language when outputting the date. Here is one example of how you can do this using Liquid:

Translate the Months:

First, we will need to create an object of Months converted from English to whichever language you'd like:

HTML
|

Now we have an object called "months" storing all the translated Months, simply change "FRE" and the translation to whichever language you'd like.

Search the Months

Now we've translated the Months we'll need to check which one needs to be outputted. Firstly assign a variable with the Month you'd like to translate, I'd like to do so with my items "release_date":{% assign current_month = this['release_date'] | date: "%B" %}

We use the "date" filter here to format the "raw" date integer to a humanized date. This follows Ruby's STRF format, read here for more info on formatting dates. We'll use "%B", as this will store the Month as a String. Now specify which language in "month_map" you're using, I've chosen French: {% assign language = "fre" %} Next, we'll use these two variables to search the "month_map" and return the translated Month: {% assign translated_month = month_map[language][current_month] %}

Format the translated Month and store in a variable:

Now we've found the translated Month we'll need to format it into a complete date, and then store this so it can be outputted:

HTML
|

We assign the Date and Year, formatting them into integer dates using the "date" filter, then we append the finished date to the variable "date_complete", you can output this like so: {{date_complete}}



Updated 07 Jan 2022
Did this page help?
Yes
No