Search code examples
javastringdatetimedata-conversion

How to parse a string and convert date values into datetime values in Java


I have a String that contains an expression like this:

final String expression = "id = 123 AND openDate < 2023-01-01 AND closeDate = 2024-01-01";

As openDate and closeDate are deprecated and got replaced by openDateTime and closeDateTime, I need to fix the expression before executing it like this:

final String newExpression = expression
        .replaceAll("\\bopenDate\\b", "openDateTime")
        .replaceAll("\\bcloseDate\\b", "closeDateTime");

The statement above results in the following expression:

"id = 123 AND openDateTime < 2023-01-01 AND closeDateTime > 2024-01-01"

The problem is that I also need to convert the actual date values into datetime so that the final expression is like this:

"id = 123 AND openDateTime < 2023-01-01 00:00 AND closeDateTime = 2024-01-01 00:00"

How do I to get the actual dates next to openDate and closeDate so that I can convert them into datetime values?


Solution

  • How about:

        final String newExpression = expression.replaceAll(
                "\\s(openDate|closeDate)\\s*([<>]=?|=)\\s*(\\d{4}-\\d{2}-\\d{2})", 
                " $1Time $2 $3 00:00");