diff --git a/fe/src/main/java/org/apache/doris/rewrite/FEFunctions.java b/fe/src/main/java/org/apache/doris/rewrite/FEFunctions.java index 6b572cc8dfd930..74a1607ae02125 100644 --- a/fe/src/main/java/org/apache/doris/rewrite/FEFunctions.java +++ b/fe/src/main/java/org/apache/doris/rewrite/FEFunctions.java @@ -38,6 +38,7 @@ import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.DateTimeFormatterBuilder; +import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; @@ -55,9 +56,15 @@ public class FEFunctions { @FEFunction(name = "datediff", argTypes = { "DATETIME", "DATETIME" }, returnType = "INT") public static IntLiteral dateDiff(LiteralExpr first, LiteralExpr second) throws AnalysisException { - long diff = getTime(first) - getTime(second); - long datediff = diff / 1000 / 60 / 60 / 24; - return new IntLiteral(datediff, Type.INT); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + try { + // DATEDIFF function only uses the date part for calculations and ignores the time part + long diff = sdf.parse(first.getStringValue()).getTime() - sdf.parse(second.getStringValue()).getTime(); + long datediff = diff / 1000 / 60 / 60 / 24; + return new IntLiteral(datediff, Type.INT); + } catch (ParseException e) { + throw new AnalysisException(e.getLocalizedMessage()); + } } @FEFunction(name = "date_add", argTypes = { "DATETIME", "INT" }, returnType = "DATETIME") diff --git a/fe/src/test/java/org/apache/doris/rewrite/FEFunctionsTest.java b/fe/src/test/java/org/apache/doris/rewrite/FEFunctionsTest.java index c2602077bd82b3..d09e35d32b9445 100644 --- a/fe/src/test/java/org/apache/doris/rewrite/FEFunctionsTest.java +++ b/fe/src/test/java/org/apache/doris/rewrite/FEFunctionsTest.java @@ -52,6 +52,17 @@ public void unixtimestampTest() { } } + @Test + public void dateDiffTest() throws AnalysisException { + IntLiteral actualResult = FEFunctions.dateDiff(new DateLiteral("2010-11-30 23:59:59", Type.DATETIME), new DateLiteral("2010-12-31", Type.DATE)); + IntLiteral expectedResult = new IntLiteral(-31); + Assert.assertEquals(expectedResult, actualResult); + + actualResult = FEFunctions.dateDiff(new DateLiteral("2010-11-30 23:59:50", Type.DATETIME), new DateLiteral("2010-12-30 23:59:59", Type.DATETIME)); + expectedResult = new IntLiteral(-30); + Assert.assertEquals(expectedResult, actualResult); + } + @Test public void dateAddTest() throws AnalysisException { DateLiteral actualResult = FEFunctions.dateAdd(new StringLiteral("2018-08-08"), new IntLiteral(1));