Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions fe/src/main/java/org/apache/doris/rewrite/FEFunctions.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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")
Expand Down
11 changes: 11 additions & 0 deletions fe/src/test/java/org/apache/doris/rewrite/FEFunctionsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down