1+ package com .github .sidhant92 .boolparser .function .arithmetic ;
2+
3+ import java .time .LocalDate ;
4+ import java .time .temporal .ChronoUnit ;
5+ import java .util .Arrays ;
6+ import java .util .List ;
7+ import com .github .sidhant92 .boolparser .constant .ContainerDataType ;
8+ import com .github .sidhant92 .boolparser .constant .DataType ;
9+ import com .github .sidhant92 .boolparser .constant .FunctionType ;
10+ import com .github .sidhant92 .boolparser .domain .EvaluatedNode ;
11+ import com .github .sidhant92 .boolparser .exception .InvalidFunctionArgument ;
12+
13+ /**
14+ * Function to calculate the number of days elapsed since a given date.
15+ * Returns a positive number for dates in the past, negative for dates in the future.
16+ *
17+ * @author sidhant.aggarwal
18+ * @since 05/03/2023
19+ */
20+ public class DaysElapsedFunction extends AbstractFunction {
21+
22+ @ Override
23+ public Object evaluate (final List <EvaluatedNode > items ) {
24+ if (items .size () != 1 ) {
25+ throw new InvalidFunctionArgument ("DAYS_ELAPSED function requires exactly one argument" );
26+ }
27+
28+ final EvaluatedNode item = items .get (0 );
29+ final Object value = item .getValue ();
30+
31+ LocalDate inputDate ;
32+ if (value instanceof LocalDate ) {
33+ inputDate = (LocalDate ) value ;
34+ } else if (value instanceof String ) {
35+ // Try to parse string as date if the DataType detection missed it
36+ try {
37+ inputDate = LocalDate .parse ((String ) value );
38+ } catch (Exception e ) {
39+ throw new InvalidFunctionArgument ("DAYS_ELAPSED function requires a valid date argument, got: " + value );
40+ }
41+ } else {
42+ throw new InvalidFunctionArgument ("DAYS_ELAPSED function requires a date argument, got: " + value .getClass ().getSimpleName ());
43+ }
44+
45+ final LocalDate today = LocalDate .now ();
46+ return ChronoUnit .DAYS .between (inputDate , today );
47+ }
48+
49+ @ Override
50+ public FunctionType getFunctionType () {
51+ return FunctionType .DAYS_ELAPSED ;
52+ }
53+
54+ @ Override
55+ public List <ContainerDataType > getAllowedContainerTypes () {
56+ return Arrays .asList (ContainerDataType .PRIMITIVE );
57+ }
58+
59+ @ Override
60+ public List <DataType > getAllowedDataTypes () {
61+ return Arrays .asList (DataType .DATE );
62+ }
63+ }
0 commit comments