Groovy: Timeduration-Subtraction evaluated from string

date, evaluate, groovy, string, subtraction

Solution

The problem is the order the operations are evaluated in:

`-1.day` is equivalent to `-(1.day)`, or `(1.day).negative()`

To solve this, you can apply parentheses to evaluate the minus operator first:

`(-1).day`

Another solution is to add a `negative()` method to the `Duration` class.

Duration.metaClass.negative = { -> 
    new Duration(-delegate.days, 
                 -delegate.hours, 
                 -delegate.minutes, 
                 -delegate.seconds, 
                 -delegate.millis) 
}

Problem

My script reads a string from a file and evaluates it to work as TimeDuration within TimeCategory. If the string starts with a "-" it throws an Exception. My reduced script: ``` import groovy.time.TimeCategory; String string = "-1.day" Date now = new Date() use(TimeCategory) { def x = new Date() + evaluate(string) println x } ``` Throws: ``` groovy.lang.MissingMethodException: No signature of method: groovy.time.Duration.negative() is applicable for argument types: () values: [] Possible solutions: notify() ``` At the moment my solution would be this: ``` import groovy.time.TimeCategory; String string = "-1.day" Date now = new Date() use(TimeCategory) { def x if(string.startsWith("-")) { string = string.substring(1) x = now - evaluate(string) } else { x = now + evaluate(string) } println x } ``` It could although do the following. But... i dont like it. I'm not sure about the consequence (will it work with different time units? "-1.day+2.hours-3.minutes"): ``` String prestring = "-1.day" String string = "0.day$prestring" ``` Any suggestions?

Original source