Ordinalize date formatting in Liquid/Jekyll (e.g. “1st”, “3rd” and “4th”)

前端 未结 1 827
不知归路
不知归路 2021-01-05 16:31

Is it possible to add day of the month suffixes to a date format in Liquid or Jekyll? For example: January 23rd or May 18th.

I\'ve referred to the Shopify wiki, but

相关标签:
1条回答
  • 2021-01-05 17:01

    The Liquid Template Engine that Jekyll uses doesn't offer the ability to ordinalize (e.g. turn "1" into "1st" and "3" into "3rd") out of the box. However, it is possible to use filters and tags to provide that functionality. The snippet below produces the day of month number with an ordanilized string appended. It also removes the leading zero for the first nine days of the month.

    {% assign d = page.date | date: "%-d" %}
    {% case d %}
      {% when "1" or "21" or "31" %}{{ d }}st
      {% when "2" or "22" %}{{ d }}nd
      {% when "3" or "23" %}{{ d }}rd
      {% else %}{{ d }}th
    {% endcase %}
    

    For a full date with month, day and year, use this:

    {% assign d = page.date | date: "%-d" %}
    {{ page.date | date: "%B" }} 
    {% case d %}{% when "1" or "21" or "31" %}{{ d }}st{% when "2" or "22" %}{{ d }}nd{% when "3" or "23" %}{{ d }}rd{% else %}{{ d }}th{% endcase %}, 
    {{ page.date | date: "%Y" }}
    

    which produces output like:

    September 21st, 2013
    

    Note: The code is split onto multiple lines to make it easier to read. It will render fine in HTML but will have extra whitespace in the source code. If that bothers you, simply move everything to one line.

    If you are interested in other date formatting options, I create this reference: Jekyll (and GitHub Pages) Liquid Date Formatting Examples

    0 讨论(0)
提交回复
热议问题