In Jekyll, I would really like to have the date format as "2nd December 2012" — i.e. with the ordinal, rather than just "2 December 2012".
I see that there's an ordinalize
function available in Ruby to do this, but I haven't had any luck combining it with Liquid and Jekyll.
How can I format dates as I would like?
I solved this by writing the following Jekyll plugin, which I placed in the _plugins
directory with an arbitrary name, e.g. date.rb
:
require 'date'
require 'facets/integer/ordinal'
module Jekyll
module DateFilter
def pretty(date)
"#{date.strftime('%e').to_i.ordinalize} #{date.strftime('%B')} #{date.strftime('%Y')}"
end
end
end
Liquid::Template.register_filter(Jekyll::DateFilter)
Then — having installed the facets
Ruby gem — I was able to use {{ post.date | pretty }}
in my site, and all was well.
In Jekyll 3.8 or higher (for example with GitHub pages) you can just use the new date_to_string
filter options and just write:
{{ page.date | date: "%I:%M %p on %A" }}
{{ page.date | date_to_string: "ordinal" }}
This will output: 12:23 PM on Friday 16th Jan 2015
For people using GitHub Pages:
If you're hosting your site on GitHub you won't be able to use modules (I believe GitHub run jekyll build
with the --safe
option which excludes modules), which means if you were to use Christopher's answer you'd have to build your site locally and then push the contents of the _site dir to GitHub.
Here's a solution to get an ordinal number/date just using Liquid which will allow you to use GitHub Pages + Jekyll in the usual way:
{% capture day %}{{ page.date | date: "%-d" }}{% endcapture %}
{% capture dayLastTwoDigits %}{{ day | modulo: 100 }}{% endcapture %}
{% if dayLastTwoDigits >= "11" and dayLastTwoDigits <= "13" %}
{% assign ordinal = "th" %}
{% else %}
{% capture dayLastDigit %}{{ day | modulo: 10 }}{% endcapture %}
{% case dayLastDigit %}
{% when "1" %}
{% assign ordinal = "st" %}
{% when "2" %}
{% assign ordinal = "nd" %}
{% when "3" %}
{% assign ordinal = "rd" %}
{% else %}
{% assign ordinal = "th" %}
{% endcase %}
{% endif %}
{% capture ordinalDay %}{{ day | append: ordinal }}{% endcapture %}
<p class="post-meta">{{ page.date | date: "%I:%M %p on %A" }} {{ ordinalDay }} {{ page.date | date: "of %b, %Y" }}{% if page.author %} • {{ page.author }}{% endif %}{% if page.meta %} • {{ page.meta }}{% endif %}</p>
This will output something like:
12:23 PM on Friday 16th of Jan, 2015
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With