Search code examples
javaspringspring-el

How to compare dates using Spring Expression Language?


Can anyone give me any examples of how to compare Dates using Spring Expression Languange (Spel)?

I have searched far and wide and nothing I find seems to fit my purpose. I'm using Java 8 and I have a response Object with a ZonedDateTime field which I somehow need to compare to a string in the form of YYYY-MM-DD -- IE: is before, is after, is equal, etc.

ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.systemDefault());
HashMap<String, Object> testHash = new HashMap<>();
testHash.put("dateField", zonedDateTime);

ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
context.setVariables(testHash);

Expression expression = parser.parseExpression("#dateField > '2016-01-01'");

The above is obviously not working. Anyone able to show me an example that does?


Solution

  • Below is the code for date comparison using Java 8 java.time package and Spring Expression Language. Hope this helps.

    import java.time.ZoneId;
    import java.time.ZonedDateTime;
    import java.time.format.DateTimeFormatter;
    import org.junit.Test;
    import org.springframework.expression.EvaluationContext;
    import org.springframework.expression.Expression;
    import org.springframework.expression.ExpressionParser;
    import org.springframework.expression.spel.standard.SpelExpressionParser;
    import org.springframework.expression.spel.support.StandardEvaluationContext;
    import junit.framework.Assert;
    
    public class TestDateSPEL {
    
    @Test
    public void testCompareDate() throws Exception {
        ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.systemDefault());
        String otherDate = "2010-12-25 12:00";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm").withZone(ZoneId.systemDefault());
        ZonedDateTime zdtOtherDate = ZonedDateTime.parse(otherDate, formatter);
        //SpEL Context
        EvaluationContext context = new StandardEvaluationContext(new ZonedDateTimeUtil());
        context.setVariable("dateOne", zonedDateTime);
        context.setVariable("dateTwo", zdtOtherDate);
        //SpEL Parser
        ExpressionParser parser = new SpelExpressionParser();
        Expression exp = parser.parseExpression("compareDate(#dateOne, #dateTwo)");
        int value = (Integer) exp.getValue(context);
        //"zonedDateTime" is after "zdtOtherDate"
        Assert.assertEquals(1, value);
      }
    }
    
    class ZonedDateTimeUtil {
    public int compareDate(ZonedDateTime dateOne, ZonedDateTime dateTwo){
        return dateOne.compareTo(dateTwo);
       }
    }