Skip to content

Commit 07c4b6a

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 7335563 commit 07c4b6a

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
@@ -4359,6 +4359,7 @@ date2isoweek(int year, int mon, int mday)
43594359
/* date2isoyear()
43604360
*
43614361
* Returns ISO 8601 year number.
4362+
* Note: zero or negative results follow the year-zero-exists convention.
43624363
*/
43634364
int
43644365
date2isoyear(int year, int mon, int mday)
@@ -4633,6 +4634,9 @@ timestamp_part(PG_FUNCTION_ARGS)
46334634

46344635
case DTK_ISOYEAR:
46354636
result = date2isoyear(tm->tm_year, tm->tm_mon, tm->tm_mday);
4637+
/* Adjust BC years */
4638+
if (result <= 0)
4639+
result -= 1;
46364640
break;
46374641

46384642
case DTK_DOW:
@@ -4829,6 +4833,9 @@ timestamptz_part(PG_FUNCTION_ARGS)
48294833

48304834
case DTK_ISOYEAR:
48314835
result = date2isoyear(tm->tm_year, tm->tm_mon, tm->tm_mday);
4836+
/* Adjust BC years */
4837+
if (result <= 0)
4838+
result -= 1;
48324839
break;
48334840

48344841
case DTK_DOW:

src/test/regress/expected/timestamp.out

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -809,7 +809,7 @@ SELECT d1 as "timestamp",
809809
Fri Feb 14 17:32:01 1997 | 1997 | 7 | 5 | 5 | 45
810810
Sat Feb 15 17:32:01 1997 | 1997 | 7 | 6 | 6 | 46
811811
Sun Feb 16 17:32:01 1997 | 1997 | 7 | 7 | 0 | 47
812-
Tue Feb 16 17:32:01 0097 BC | -96 | 7 | 2 | 2 | 47
812+
Tue Feb 16 17:32:01 0097 BC | -97 | 7 | 2 | 2 | 47
813813
Sat Feb 16 17:32:01 0097 | 97 | 7 | 6 | 6 | 47
814814
Thu Feb 16 17:32:01 0597 | 597 | 7 | 4 | 4 | 47
815815
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
@@ -918,7 +918,7 @@ SELECT d1 as timestamptz,
918918
Fri Feb 14 17:32:01 1997 PST | 1997 | 7 | 5 | 5 | 45
919919
Sat Feb 15 17:32:01 1997 PST | 1997 | 7 | 6 | 6 | 46
920920
Sun Feb 16 17:32:01 1997 PST | 1997 | 7 | 7 | 0 | 47
921-
Tue Feb 16 17:32:01 0097 PST BC | -96 | 7 | 2 | 2 | 47
921+
Tue Feb 16 17:32:01 0097 PST BC | -97 | 7 | 2 | 2 | 47
922922
Sat Feb 16 17:32:01 0097 PST | 97 | 7 | 6 | 6 | 47
923923
Thu Feb 16 17:32:01 0597 PST | 597 | 7 | 4 | 4 | 47
924924
Tue Feb 16 17:32:01 1097 PST | 1097 | 7 | 2 | 2 | 47

0 commit comments

Comments
 (0)