Addition or subtraction on date
We have a nice culture in our company where we sit together on every alternate Saturday and either share new things or we just learn about the technology we are using. This time we discussed about Groovy Meta Programming tricks and we watched the Meta Programming video of Jeff Brown. In that video the handling of Missing Method was really helpful.
Today I got the use case in my project where I need to add/minus the years, months, weeks etc in date. I searched about such methods but couldn’t find the best solution, though Gregorian calendar is one of the option. Then I found a very nice blog on getting past future dates from Aman Aggarwal. So I added the functionality given in the blog into the Date class using Meta Programming
[java]
Date.metaClass.methodMissing = {String methodName, args ->
List interceptableMethods = [‘addYears’, ‘addMonths’, ‘addWeeks’, ‘addDays’, ‘addHours’, ‘addMinutes’, ‘addSeconds’, ‘minusYears’, ‘minusMonths’, ‘minusWeeks’, ‘minusDays’, ‘minusHours’, ‘minusMinutes’, ‘minusSeconds’]
if (methodName in interceptableMethods && args[0] instanceof Integer) {
String method = methodName.replace(‘add’, ”)
method = method.replace(‘minus’, ”)
def impl = {methodArg ->
Date date
use(org.codehaus.groovy.runtime.TimeCategory) {
if (methodName.contains(‘add’)) {
date = delegate + methodArg."get${method}"()
}
else {
date = delegate – methodArg."get${method}"()
}
}
return date
}
Date.metaClass."${methodName}" = impl
impl(* args)
}
else {
throw new MissingMethodException(methodName, Date, args)
}
}
[/java]
I added the above code in my Grails application Bootstrap file and now I can just call the methods like
[java]
Date date=new Date()
date=date.addYears(2)
date=date.addMonths(4)
date=date.minusHours(36)
[/java]
Hope it helps
Uday Pratap Singh
uday@intelligrape.com
Something like:
Date.mixin = org.codehaus.groovy.runtime.TimeCategory
I will give a try. Thanks for the suggestion.
Why don’t you just use the “mixin” mechanism?