Skip to content

Commit c965c42

Browse files
committed
Fix EXTRACT(ISOYEAR FROM timestamp) for years BC.
The test cases added by commit 26ae3aa exposed an old oversight in timestamp[tz]_part: they didn't correct the result of date2isoyear() for BC years, so that we produced an off-by-one answer for such years. Fix that, and back-patch to all supported branches. Discussion: https://postgr.es/m/SG2PR06MB37762CAE45DB0F6CA7001EA9B6550@SG2PR06MB3776.apcprd06.prod.outlook.com
1 parent f3cf330 commit c965c42

File tree

3 files changed

+9
-2
lines changed

3 files changed

+9
-2
lines changed

src/backend/utils/adt/timestamp.c

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4125,6 +4125,7 @@ date2isoweek(int year, int mon, int mday)
41254125
/* date2isoyear()
41264126
*
41274127
* Returns ISO 8601 year number.
4128+
* Note: zero or negative results follow the year-zero-exists convention.
41284129
*/
41294130
int
41304131
date2isoyear(int year, int mon, int mday)
@@ -4399,6 +4400,9 @@ timestamp_part(PG_FUNCTION_ARGS)
43994400

44004401
case DTK_ISOYEAR:
44014402
result = date2isoyear(tm->tm_year, tm->tm_mon, tm->tm_mday);
4403+
/* Adjust BC years */
4404+
if (result <= 0)
4405+
result -= 1;
44024406
break;
44034407

44044408
case DTK_DOW:
@@ -4595,6 +4599,9 @@ timestamptz_part(PG_FUNCTION_ARGS)
45954599

45964600
case DTK_ISOYEAR:
45974601
result = date2isoyear(tm->tm_year, tm->tm_mon, tm->tm_mday);
4602+
/* Adjust BC years */
4603+
if (result <= 0)
4604+
result -= 1;
45984605
break;
45994606

46004607
case DTK_DOW:

src/test/regress/expected/timestamp.out

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -822,7 +822,7 @@ SELECT d1 as "timestamp",
822822
Fri Feb 14 17:32:01 1997 | 1997 | 7 | 5 | 5 | 45
823823
Sat Feb 15 17:32:01 1997 | 1997 | 7 | 6 | 6 | 46
824824
Sun Feb 16 17:32:01 1997 | 1997 | 7 | 7 | 0 | 47
825-
Tue Feb 16 17:32:01 0097 BC | -96 | 7 | 2 | 2 | 47
825+
Tue Feb 16 17:32:01 0097 BC | -97 | 7 | 2 | 2 | 47
826826
Sat Feb 16 17:32:01 0097 | 97 | 7 | 6 | 6 | 47
827827
Thu Feb 16 17:32:01 0597 | 597 | 7 | 4 | 4 | 47
828828
Tue Feb 16 17:32:01 1097 | 1097 | 7 | 2 | 2 | 47

src/test/regress/expected/timestamptz.out

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -913,7 +913,7 @@ SELECT d1 as timestamptz,
913913
Fri Feb 14 17:32:01 1997 PST | 1997 | 7 | 5 | 5 | 45
914914
Sat Feb 15 17:32:01 1997 PST | 1997 | 7 | 6 | 6 | 46
915915
Sun Feb 16 17:32:01 1997 PST | 1997 | 7 | 7 | 0 | 47
916-
Tue Feb 16 17:32:01 0097 PST BC | -96 | 7 | 2 | 2 | 47
916+
Tue Feb 16 17:32:01 0097 PST BC | -97 | 7 | 2 | 2 | 47
917917
Sat Feb 16 17:32:01 0097 PST | 97 | 7 | 6 | 6 | 47
918918
Thu Feb 16 17:32:01 0597 PST | 597 | 7 | 4 | 4 | 47
919919
Tue Feb 16 17:32:01 1097 PST | 1097 | 7 | 2 | 2 | 47

0 commit comments

Comments
 (0)