Skip to content

date

The date filter is a powerful tool for formatting dates and times into various string representations. It provides extensive control over the output format by leveraging strftime (string format time) syntax, a standard way to define date and time patterns.

Functionality

  • Date/Time Values: Takes a date, time, or datetime value as input. You can directly use a DateTime object, or provide a string representing a date/time value.
  • Format String (Optional): Accepts an optional format string that specifies how the date/time should be displayed. If not provided, a default format is used (typically ISO 8601 format).
  • Strftime Syntax: The format string uses strftime directives, which are special codes representing different components of a date/time (e.g., %Y for year, %m for month, %d for day). Refer to strftime documentation for a complete list of directives.
  • Output: Returns a formatted string representing the date/time value according to the format string.

Syntax

Code snippet

    {{ input_datetime | date: format_string }}

Arguments

  • format_string (optional): A string specifying the desired format using strftime directives.

Code Samples

Example 1: Basic Date Formatting

    {% assign today = "now" | date: "%Y-%m-%dT%H:%M:%S%z" | date: "%Y-%m-%dT%H:%M:%S%z" %}

    {{ today | date: "%B %d, %Y" }} 
Output:
May 23, 2024
Example 2: Custom Date and Time Format
    {% assign now = "now" | date: "%Y-%m-%dT%H:%M:%S%z" | date: "%Y-%m-%dT%H:%M:%S%z" %}

    {{ now | date: "%A, %B %e, %Y at %I:%M %p" }}

Output:

Thursday, May 23, 2024 at 9:30 AM
Example 3: Using Default Format (No Argument)

    {% assign date_string = "2023-12-25T15:30:00Z" %}
    {% assign parsed_date = date_string | date: "%Y-%m-%dT%H:%M:%S%z" | date: "%Y-%m-%dT%H:%M:%S%z" %}

    {{ parsed_date | date }} 
Output:
2023-12-25T15:30:00+00:00
Outliers and Special Cases

  • Invalid Format Strings: If the format_string contains invalid strftime directives, the filter might throw an error or produce unexpected results.
  • Non-Date/Time Input: If the input is not a valid date or time value, the filter might attempt to convert it or return an error.
  • Time Zones: The date filter might respect the time zone of the input date/time, or it might use a default time zone (such as UTC). If you need explicit control over time zones, consider using the time_zone filter in conjunction with date.

Key Points

  • The date filter is a powerful tool for customizing the presentation of dates and times within your templates.
  • Mastering strftime format codes gives you fine-grained control over the output.
  • Pay attention to the input data type and potential time zone issues to ensure accurate formatting.