Code

Ticket #3311: natural_day_v3.diff

File natural_day_v3.diff, 1.4 KB (added by Jyrki Pulliainen <jyrki.pulliainen@…>, 7 years ago)

New patch

Line 
1Index: contrib/humanize/templatetags/humanize.py
2===================================================================
3--- contrib/humanize/templatetags/humanize.py   (revision 4537)
4+++ contrib/humanize/templatetags/humanize.py   (working copy)
5@@ -1,4 +1,8 @@
6 from django import template
7+from django.utils.translation import gettext as _
8+from django.template import defaultfilters
9+from django.conf import settings
10+from datetime import date, timedelta
11 import re
12 
13 register = template.Library()
14@@ -62,3 +66,28 @@
15         return value
16     return ('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine')[value-1]
17 register.filter(apnumber)
18+
19+def naturalday(value, arg=None):
20+    """
21+    For date values that are tomorrow, today or yesterday compared to
22+    present day returns representing string. Otherwise, returns a string
23+    formatted according to settings.DATE_FORMAT.
24+    """
25+    try:
26+        value = date(value.year, value.month, value.day)
27+    except AttributeError:
28+        # Passed value wasn't a date object
29+        return value
30+    except ValueError:
31+        # Date arguments out of range
32+        return value
33+    today = date.today()
34+    delta = timedelta(days=1)
35+    if value == today:
36+        return _('today')
37+    elif value == today + delta:
38+        return _('tomorrow')
39+    elif value == today - delta:
40+        return _('yesterday')
41+    return defaultfilters.date(value, arg)
42+register.filter(naturalday)