diff --git a/velox/functions/prestosql/DateTimeFunctions.h b/velox/functions/prestosql/DateTimeFunctions.h index 4cd881817bfa..51eb5f03d89f 100644 --- a/velox/functions/prestosql/DateTimeFunctions.h +++ b/velox/functions/prestosql/DateTimeFunctions.h @@ -213,9 +213,11 @@ struct WeekFunction : public InitSessionTimezone, auto firstMondayOfYear = 1 + (mondayOfWeek + kDaysInWeek - 1) % kDaysInWeek; + // A long year is any year ending on Thursday and any leap year ending on + // Friday. if ((util::isLeapYear(time.tm_year + 1900 - 1) && - firstMondayOfYear == 2) || - firstMondayOfYear == 3 || firstMondayOfYear == 4) { + firstMondayOfYear == 3) || + firstMondayOfYear == 4) { week = 53; } else { week = 52; diff --git a/velox/functions/prestosql/tests/DateTimeFunctionsTest.cpp b/velox/functions/prestosql/tests/DateTimeFunctionsTest.cpp index 0a87e93549c8..a0a590ce90a0 100644 --- a/velox/functions/prestosql/tests/DateTimeFunctionsTest.cpp +++ b/velox/functions/prestosql/tests/DateTimeFunctionsTest.cpp @@ -500,6 +500,22 @@ TEST_F(DateTimeFunctionsTest, weekDate) { EXPECT_EQ(1, weekDate("1970-01-01")); EXPECT_EQ(1, weekDate("0001-01-01")); EXPECT_EQ(52, weekDate("9999-12-31")); + + // Test various cases where the last week of the previous year extends into + // the next year. + + // Leap year that ends on Thursday. + EXPECT_EQ(53, weekDate("2021-01-01")); + // Leap year that ends on Friday. + EXPECT_EQ(53, weekDate("2005-01-01")); + // Leap year that ends on Saturday. + EXPECT_EQ(52, weekDate("2017-01-01")); + // Common year that ends on Thursday. + EXPECT_EQ(53, weekDate("2016-01-01")); + // Common year that ends on Friday. + EXPECT_EQ(52, weekDate("2022-01-01")); + // Common year that ends on Saturday. + EXPECT_EQ(52, weekDate("2023-01-01")); } TEST_F(DateTimeFunctionsTest, week) {