Change date format on a template

↘锁芯ラ 提交于 2020-01-25 20:45:28

问题


I'm using the Foundry template on Squarespace and I need to change the date format on post pages from english to portuguese. Instead of "May 6" I need "6 Mai". In Brazil we use the pattern dd/mm/yyyy. In this case I just want the day and month, and also translate all the months (to: Jan, Fev, Mar, Abr, Mai, Jun, Jul, Ago, Set, Out, Nov, Dez).

I already saw people solving this for others languages there. But not to portuguese or on the Foundry template. It's possible to make a code-injection on Squarespace, on the head or footer. I just need a Javascript that can do that, overwriting the theme's default date format.


回答1:


I would approach it via the following Javascript, inserted via code injection. Note that although some of the month abbreviations are the same, I've included them for clarity and so that it may be more reusable for others. Also, the abbreviations I've used for the keys (that is, the original month abbreviations) may not be what Squarespace actually uses, so they may need to be updated.

<script>
    (function() {
        var dates = document.getElementsByClassName("dt-published date-highlight");
        var newDate;
        var i,I;
        // Create object with 'source' keys on the left, and 'output' values on the right.
        var months = {
            "Jan":"Jan",
            "Feb":"Fev",
            "Mar":"Mar",
            "Apr":"Abr",
            "May":"Mai",
            "Jun":"Jun",
            "Jul":"Jul",
            "Aug":"Ago",
            "Sep":"Set",
            "Oct":"Out",
            "Nov":"Nov",
            "Dec":"Dez"
        };
        // Loop through all dates, replacing months and reordering display.
        //  - Trim extra white space from beginning and end of date.
        //  - Replace multiple consecutive spaces with a single space.
        //  - Split by space into an array.
        //  - Replace month text based on 'months' object key:value pairs.
        //  - Convert array to string, rearranging display order of elements.
        //  - Set new date HTML.
        for (i=0, I=dates.length; i<I; i++) {
            newDate = dates[i].innerHTML.trim();
            newDate = newDate = newDate.replace(/  +/g, ' ');
            newDate = newDate.split(" ");
            newDate[0] = months[newDate[0]];
            newDate = newDate[1] + " " + newDate[0];
            dates[i].innerHTML = newDate;
        }
    })();
</script>


来源:https://stackoverflow.com/questions/43818671/change-date-format-on-a-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!