Question

I'm using Django's naturalday template tag, but how do I format the date string if the supplied date is not today, tomorrow or yesterday?

This is my template string:

 Date: {{ result_date|naturalday }}

If result_date is today, yesterday or tomorrow, then the template displays the natural string. But if it's 10 days ago, how can I control the formatting of the date to display as "July 25"?

The docs say:

For dates that are the current day or within one day, return “today”, “tomorrow” or “yesterday”, as appropriate. Otherwise, format the date using the passed in format string.

What does "the passed in format string" mean?

Was it helpful?

Solution

Pass the format after the :, like in date filter:

Date: {{ result_date|naturalday:"F d" }}
  • F is a textual representation of month, e.g. July.
  • d is a day of the month, 2 digits with leading zeros, e.g. 25.

Hope that helps.

OTHER TIPS

You should check the example:

Examples (when ‘today’ is 17 Feb 2007):

  • 16 Feb 2007 becomes yesterday.
  • 17 Feb 2007 becomes today.
  • 18 Feb 2007 becomes tomorrow.
  • Any other day is formatted according to given argument or the DATE_FORMAT setting if no argument is given.

Then about DATE_FORMAT:

Default: 'N j, Y' (e.g. Feb. 4, 2003)

The default formatting to use for displaying date fields in any part of the system. Note that if USE_L10N is set to True, then the locale-dictated format has higher precedence and will be applied instead. See allowed date format strings.

So it will fall back to Feb. 17, 2007 if no format string argument is provided and DATE_FORMAT is not specified in settings.py.

The normal fall back format string is provided in alecxe's answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top