Ticket #3311: natural_day_v4.diff

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

Naturalday patch with the time delta

  • contrib/humanize/templatetags/humanize.py

     
    11from django import template
     2from django.utils.translation import gettext as _
     3from django.template import defaultfilters
     4from django.conf import settings
     5from datetime import date, timedelta
    26import re
    37
    48register = template.Library()
     
    6266        return value
    6367    return ('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine')[value-1]
    6468register.filter(apnumber)
     69
     70def naturalday(value, arg=None):
     71    """
     72    For date values that are tomorrow, today or yesterday compared to
     73    present day returns representing string. Otherwise, returns a string
     74    formatted according to settings.DATE_FORMAT.
     75    """
     76    try:
     77        value = date(value.year, value.month, value.day)
     78    except AttributeError:
     79        # Passed value wasn't a date object
     80        return value
     81    except ValueError:
     82        # Date arguments out of range
     83        return value
     84    delta = value - date.today()
     85    if delta.days == 0:
     86        return _('today')
     87    elif delta.days == 1:
     88        return _('tomorrow')
     89    elif delta.days == -1:
     90        return _('yesterday')
     91    return defaultfilters.date(value, arg)
     92register.filter(naturalday)
Back to Top