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

旧街凉风 提交于 2019-12-19 03:20:04

问题


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 I'm shocked to see that there's no formatting there for it. Surely something that simple should be? :/


回答1:


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



来源:https://stackoverflow.com/questions/18892909/ordinalize-date-formatting-in-liquid-jekyll-e-g-1st-3rd-and-4th

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