Search code examples
datejekyllfilenames

How can I use Liquid / Jekyll to extract the date from an image's filename?


I understand that Jekyll auto-extracts the date from a post's filename.

How to the same with an image's filename please?

Let's assume the following format of the image filenames:

  • 2020-12-10_A_the_rest_of_the_filename_of_the_image.jpg
  • 2020-12-10_B_the_rest_of_the_filename_of_the_image.jpg
  • 2020-12-10_C_the_rest_of_the_filename_of_the_image.jpg
  • 2021-01-04_A_the_rest_of_the_filename_of_the_image.jpg
  • 2021-01-04_B_the_rest_of_the_filename_of_the_image.jpg

Thus it only includes YYYY-MM-DD and then some further sorting/index information (such as a, b, c, ...), and then the rest of the image's filename.

The main goal is to be able to extract the date as follows:

  • 10 Dec, 2020
  • 10 Dec, 2020
  • 10 Dec, 2020
  • 04 Jan, 2021
  • 04 Jan, 2021

Solution

  • To get the date part out of you file name, you could either use the slice or split filter.
    If you do use the split filter, you will want to use the first filter, in order to take the first element of the created array.

    To get the date format you want, you can just use the date filter.

    1. With slice:
      {{ "2020-12-10_A_the_rest_of_the_filename_of_the_image.jpg" | slice: 0, 10 | date: "%d %b, %Y" }}
      
    2. With split:
      {{ "2020-12-10_A_the_rest_of_the_filename_of_the_image.jpg" | split: "_" | first | date: "%d %b, %Y" }}
      

    Those both results in: 10 Dec, 2020


    Additionally, you might want to read the Ruby documentation about the date format available at: https://ruby-doc.org/stdlib-2.4.1/libdoc/time/rdoc/Time.html#method-c-strptime