CASE: check date for leap year or not

If you wish to check a certain date, and whether or not it falls into a “leap year”, you can do so with this code:

{% comment %}let user input the date, to check for leap year or not{% endcomment %}
{% input custom.some.dag as:date %}

{% comment %}calculate amounts of days of the year the date resides in{% endcomment %}
{% assign days_in_year = custom.some.dag | date:"31/12/%Y" | date:"%j" %}

{% comment %}the local var will output either 365 OR 366{% endcomment %}
{{ days_in_year }} 

All credits to @Peter for this! :clap:
see Leap year : function available

Info on date filters and what they do precisely, can be found here eg.

If you’re looking for a more extensive function that automatically checks if the current bookyear contains a leap day you can use the following function (it also covers any edge cases but you can always adjust it as you see fit).

Next to the general rule of a leap year occurring every 4 years there’s an additional correction. This correction states that years that are evenly divisible by 100 are not leap years, unless they are also evenly divisible by 400.

This means that the following years are not leap years, as they ar evenly divisible by 100, but not 400:
1700, 1800, 1900, 2100, 2200, 2300, 2500, 2600

And the following years are leap years: 1600, 2000, 2400

So, to make our check cover these edge cases, make it independent of the way the bookyear is formed (broken/extended bookyears) and avoid immediately firing a loop over every month, we’ll first loop over the calendar years that are in the period:

 {% for year in period.calendar_years %}
   {% assign int_year = year.start_date | date:"%Y" %}
   {% assign modulo_year_400 = int_year | modulo:400 %}
   {% assign modulo_year_100 = int_year | modulo:100 %}
   {% assign modulo_year_4 = int_year | modulo:4 %}
      
   {% if modulo_year_400 == 0 %}
     {% assign period_has_leap_year = true %}
     {% break %}
   {% elsif modulo_year_4 == 0 and modulo_year_100 != 0 %}
     {% assign period_has_leap_year = true %}
     {% break %}
   {% endif %}
 {% endfor %}

Once we’ve determined that one of the calendar years is a leap year, we can then check if a leap day is present in the bookyear:

{% assign period_has_leap_day = false %}
{% if period_has_leap_year %}
  {% comment %}Check if the leap day is in the bookyear{% endcomment %}
  {% assign month_end_dates_array = period.month_end_dates %}
  {% for month in month_end_dates_array %}
    {% assign filtered_month = month | date:"%m-%d" %}
    {% if filtered_month == '02-29' %}
      {% assign period_has_leap_day = true %}
      {% break %}
    {% endif %}
  {% endfor %}
{% endif %}
1 Like