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
DateTimeobject, 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.,
%Yfor year,%mfor month,%dfor 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
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" }}
{% 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:
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 }}
- Invalid Format Strings: If the
format_stringcontains 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
datefilter 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 thetime_zonefilter in conjunction withdate.
Key Points
- The
datefilter 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.