Skip to content

format_date

The format_date filter is designed to format a date/time value according to a specified format string. It provides flexibility in how dates and times are displayed in your templates.

Functionality

  • Date/Time Values: Takes a date, time, or datetime value as input.
  • Format String: Requires a format string that defines how the date/time should be displayed. The format string uses standard .NET date and time format specifiers (e.g., "yyyy-MM-dd", "HH:mm:ss", "dddd, MMMM dd, yyyy").
  • Culture (Optional): Accepts an optional culture string (e.g., "en-US", "fr-FR") to control the formatting conventions (e.g., date separators, month names). Defaults to the current culture if not provided.
  • Output: Returns a formatted string representing the date/time value.

Syntax

    {{ input_date | format_date: format_string, culture }}

Arguments

  • format_string: The format string to use for displaying the date/time.
  • culture (optional): A string specifying the culture to use for formatting (e.g., "en-US").

Code Samples

Example 1: Formatting a Date

    {% assign today = "now" | date: "%Y-%m-%dT%H:%M:%S%z" | date: "%Y-%m-%dT%H:%M:%S%z" %}
    {{ today | format_date: "yyyy-MM-dd" }}
Output:
2024-05-22
Example 2: Formatting a Date with Time

    {% assign now = "now" | date: "%Y-%m-%dT%H:%M:%S%z" | date: "%Y-%m-%dT%H:%M:%S%z" %}
    {{ now | format_date: "MMMM d, yyyy h:mm tt" }}

Output:

May 22, 2024 9:04 PM
Example 3: Formatting a Date with a Different Culture
    {% assign event_date = "now" | date: "%Y-%m-%dT%H:%M:%S%z" | date: "%Y-%m-%dT%H:%M:%S%z" %}
    {{ event_date | format_date: "dd/MM/yyyy", "fr-FR" }}

Output:

22/05/2024
Outliers and Special Cases

  • Invalid Format String: If the provided format string is not valid, an error might occur.
  • Invalid Culture String: If the provided culture string is not valid, the filter might use the default culture or throw an error.
  • Non-Date/Time Input: If the input is not a date, time, or datetime value, the filter might attempt to convert it or return an error.

Key Points

  • The format_date filter is a powerful tool for customizing the appearance of dates and times in your templates.
  • Familiarize yourself with the standard .NET date and time format specifiers to create the desired output format.
  • Consider the locale of your users and provide appropriate culture settings for accurate formatting.
  • Test your format strings and culture settings thoroughly to avoid errors and unexpected results.