Easily translate date in Webflow

Hello guys,

I’ve been using this code for every project now to translate dynamic words like months or days in Webflow.
Credits goes to i think @bart who gave the base of the code to @vincent

The way it works :

  • Simply add combo class classdate on any text block you want to translate.
  • Change the words in the code below if you to change de translation or add a new line you want to translate in monthsEn and the translation in monthsFr
  • Add the script bellow in the footer of your project.

Enjoy

<script>
// config
var dateclass = 'classdate';

$(document).ready(function() {
  var wfdc = $('.' + dateclass);

  wfdc.each(function() {
    var wfdctxt = $(this).text();

    var monthsEn = [
      'January',
      'February',
      'March',
      'April',
      'May',
      'June',
      'July',
      'August',
      'September',
      'October',
      'November',
      'December',
      'Monday',
      'Tuesday',
      'Wednesday',
      'Thursday',
      'Friday',
      'Saturday',
      'Sunday'
    ];

    var monthsFr = [
      'janvier',
      'février',
      'mars',
      'avril',
      'mai',
      'juin',
      'juillet',
      'aout',
      'septembre',
      'octobre',
      'novembre',
      'décembre',
      'Lundi',
      'Mardi',
      'Mercredi',
      'Jeudi',
      'Vendredi',
      'Samedi',
      'Dimanche'
    ];

    for (var i = 0; i < monthsEn.length; i++) {
      wfdctxt = wfdctxt.replace(monthsEn[i], monthsFr[i]);
    }

    $(this).text(wfdctxt);
  });
});
</script>
9 Likes

This is case-sensitive though. I suggest this:

wfdctxt = wfdctxt.toLowerCase().replace(monthsEn[i].toLowerCase(), monthsFr[i]);
1 Like

Thanks for sharing this :raised_hands:

There is another way but with a dependency, using Luxon’s small JS package.

  1. Insert the following script on the head code of your project (or page):
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/2.4.0/luxon.min.js" integrity="sha512-v1zUTZ9zv9Wb2scL/ANxXM6m7yegm/W5SN8SRHNFADdZIuSFFkrEBjNxO803DdFkjoCcJ88g1WHRVlLN6K/O1A==" crossorigin="anonymous" referrerpolicy="no-referrer" async></script>
  1. Insert the following script on the footer code of the desired page (or even the whole project if needed):
<script>
function translateDate(o,n,l) {
	let DateTime = luxon.DateTime
	let x = document.getElementsByClassName("luxon");
	let i;
	for (i = 0; i < x.length; i++) {
    x[i].innerText = DateTime.fromFormat(x[i].innerText, o).setLocale(l).toFormat(n);
    }
}

Webflow.push(function() {
translateDate("LLL dd, yyyy","dd LLLL yyyy","fr")
});
</script>
  1. Configure the script. The translateDate() function needs 3 arguments: old format (o), new format (n), locale (l). On the example below modify the following piece of code accordingly.
translateDate("LLL dd, yyyy","dd LLLL yyyy","fr") 

This changes “May 1st, 2022” to “1er mai 2022”. Feel free to play around with time tokens and locales..

  1. Add the class attribute “luxon” to the HTML element which contains the original date. Please note that the code replaces any text contained within that element, so please target one that only contains the date.

  2. Publish your website. Note that it won’t display the translation within the designer.

Feel free to tweak the code, adjust it to your own needs! I didn’t need more than that, so I kept it to the bare minimums. The main advantage of that method is that it’s totally automatic and you can do fairly advanced manipulations.

Please don’t ask me why Webflow does not implement such a simple feature :shushing_face:

1 Like

This is great! Many thanks :laughing:

@zbrah & @bart @vincent

This is amazing, thanks!
Just saved me so much time.

Hi guys, I hope you’re well.

I’m trying to use that code with Finsweet’s CMS Load, but it’s not working.
Basically, the content that shows after clicking on the Load More button doesn’t translate.
Has anyone already had this problem?

Thank you
@zbrah @vincent

You need to craft a JS script that is re-running the date translation JS each time there’s a change on the page. Ask ChatGPT, it’s good at that.

1 Like

In case anyone ever needs it, the following (English to Dutch translation) script worked for me with Finsweet’s CMS Load, in all browsers. Don’t forget to assign a class called “date” to the elements that need translation.

<script>

// Example date and day translation function from English to Dutch
function translateDateToDutch(observer) {
    // Temporarily stop observing while we change the DOM
    if (observer) observer.disconnect();

    const dateElements = document.querySelectorAll('.date'); // Adjust this selector if necessary
    if (dateElements.length === 0) {
        console.log("No date elements found!");
    }

    dateElements.forEach(element => {
        const englishDate = element.textContent.trim();
        console.log("Translating date:", englishDate); // Log the date we're translating

        // Simple month and day translation
        const translatedDate = englishDate
            // Translate months
            .replace('January', 'januari')
            .replace('February', 'februari')
            .replace('March', 'maart')
            .replace('April', 'april')
            .replace('May', 'mei')
            .replace('June', 'juni')
            .replace('July', 'juli')
            .replace('August', 'augustus')
            .replace('September', 'september')
            .replace('October', 'oktober')
            .replace('November', 'november')
            .replace('December', 'december')
            // Translate days of the week
            .replace('Monday', 'maandag')
            .replace('Tuesday', 'dinsdag')
            .replace('Wednesday', 'woensdag')
            .replace('Thursday', 'donderdag')
            .replace('Friday', 'vrijdag')
            .replace('Saturday', 'zaterdag')
            .replace('Sunday', 'zondag');
        
        element.textContent = translatedDate;
        console.log("Translated to:", translatedDate); // Log the translated date
    });

    // Reconnect the observer after the DOM changes are made
    if (observer) observer.observe(document.body, { childList: true, subtree: true });
}

// Function to observe DOM changes and re-run translation
function observeDOMChanges() {
    const targetNode = document.body; // Adjust target node if necessary
    const config = { childList: true, subtree: true }; // Watching for changes in the DOM subtree

    const callback = function(mutationsList, observer) {
        console.log("DOM changes detected!");
        for (let mutation of mutationsList) {
            if (mutation.type === 'childList') {
                translateDateToDutch(observer); // Re-run the translation function
            }
        }
    };

    const observer = new MutationObserver(callback);
    observer.observe(targetNode, config);
    console.log("Started observing DOM changes");

    // Initial translation on page load
    translateDateToDutch(observer);
}

// Start observing changes on the page
observeDOMChanges();

</script>
2 Likes