From 34363a391bad5a007f2ab35a6d8c4ece4c3234f6 Mon Sep 17 00:00:00 2001 From: Nick Pope Date: Mon, 10 May 2021 15:33:48 +0100 Subject: [PATCH] Fixed #32735 -- Made DateFormat.Y() return a zero-padded year. --- django/utils/dateformat.py | 4 ++-- docs/ref/templates/builtins.txt | 2 +- tests/utils_tests/test_dateformat.py | 6 +++++- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/django/utils/dateformat.py b/django/utils/dateformat.py index 38e89c47bb..4833b5af2c 100644 --- a/django/utils/dateformat.py +++ b/django/utils/dateformat.py @@ -313,8 +313,8 @@ class DateFormat(TimeFormat): return '%02d' % (self.data.year % 100) def Y(self): - "Year, 4 digits; e.g. '1999'" - return self.data.year + """Year, 4 digits with leading zeros; e.g. '1999'.""" + return '%04d' % self.data.year def z(self): """Day of the year, i.e. 1 to 366.""" diff --git a/docs/ref/templates/builtins.txt b/docs/ref/templates/builtins.txt index 1dd554aa13..e468b9c62e 100644 --- a/docs/ref/templates/builtins.txt +++ b/docs/ref/templates/builtins.txt @@ -1367,7 +1367,7 @@ Format character Description Example output ``t`` Number of days in the given month. ``28`` to ``31`` **Year** ``y`` Year, 2 digits with leading zeros. ``'00'`` to ``'99'`` -``Y`` Year, 4 digits. ``'1999'`` +``Y`` Year, 4 digits with leading zeros. ``'0001'``, ..., ``'1999'``, ..., ``'9999'`` ``L`` Boolean for whether it's a leap year. ``True`` or ``False`` ``o`` ISO-8601 week-numbering year, ``'1999'`` corresponding to the ISO-8601 week diff --git a/tests/utils_tests/test_dateformat.py b/tests/utils_tests/test_dateformat.py index c6d3ded80f..f57c67078f 100644 --- a/tests/utils_tests/test_dateformat.py +++ b/tests/utils_tests/test_dateformat.py @@ -166,7 +166,7 @@ class DateFormatTests(SimpleTestCase): 'Sun, 08 Jul 1979 22:00:00 +0100', ) - def test_year_before_1000(self): + def test_y_format_year_before_1000(self): tests = [ (476, '76'), (42, '42'), @@ -179,6 +179,10 @@ class DateFormatTests(SimpleTestCase): expected_date, ) + def test_Y_format_year_before_1000(self): + self.assertEqual(dateformat.format(datetime(1, 1, 1), 'Y'), '0001') + self.assertEqual(dateformat.format(datetime(999, 1, 1), 'Y'), '0999') + def test_twelve_hour_format(self): tests = [ (0, '12'),