diff --git a/hc/front/templatetags/hc_extras.py b/hc/front/templatetags/hc_extras.py index bdc304d2..10ebcbee 100644 --- a/hc/front/templatetags/hc_extras.py +++ b/hc/front/templatetags/hc_extras.py @@ -3,28 +3,29 @@ from django import template register = template.Library() -@register.filter -def hc_duration(td): - total = int(td.total_seconds() / 60) - total, m = divmod(total, 60) - total, h = divmod(total, 24) - o, rem = divmod(total, 30) - w, d = divmod(rem, 7) - - result = "" - if o: - result += "1 month " if w == 0 else "%d months " % w +class Unit(object): + def __init__(self, name, nsecs): + self.name = name + self.plural = name + "s" + self.nsecs = nsecs - if w: - result += "1 week " if w == 1 else "%d weeks " % w +MINUTE = Unit("minute", 60) +HOUR = Unit("hour", MINUTE.nsecs * 60) +DAY = Unit("day", HOUR.nsecs * 24) +WEEK = Unit("week", DAY.nsecs * 7) +MONTH = Unit("month", DAY.nsecs * 30) - if d: - result += "1 day " if d == 1 else "%d days " % d - if h: - result += "1 hour " if h == 1 else "%d hours " % h +@register.filter +def hc_duration(td): + remaining_seconds = int(td.total_seconds()) + result = [] - if m: - result += "1 minute " if m == 1 else "%d minutes " % m + for unit in (MONTH, WEEK, DAY, HOUR, MINUTE): + v, remaining_seconds = divmod(remaining_seconds, unit.nsecs) + if v == 1: + result.append("1 %s" % unit.name) + elif v > 1: + result.append("%d %s" % (v, unit.plural)) - return result + return " ".join(result) diff --git a/hc/front/tests/test_hc_extras.py b/hc/front/tests/test_hc_extras.py new file mode 100644 index 00000000..da1d90cb --- /dev/null +++ b/hc/front/tests/test_hc_extras.py @@ -0,0 +1,23 @@ +from datetime import timedelta as td +from unittest import TestCase +from hc.front.templatetags.hc_extras import hc_duration + + +class HcExtrasTestCase(TestCase): + + def test_hc_duration_works(self): + samples = [ + (60, "1 minute"), + (120, "2 minutes"), + (3600, "1 hour"), + (3660, "1 hour 1 minute"), + (86400, "1 day"), + (604800, "1 week"), + (2419200, "4 weeks"), + (2592000, "1 month"), + (3801600, "1 month 2 weeks") + ] + + for seconds, expected_result in samples: + result = hc_duration(td(seconds=seconds)) + self.assertEqual(result, expected_result)