Browse Source

Fixed #32735 -- Made DateFormat.Y() return a zero-padded year.

Nick Pope 3 years ago
parent
commit
34363a391b

+ 2 - 2
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."""

+ 1 - 1
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

+ 5 - 1
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'),