1

I'm becoming familiar with Groovy's TimeCategory and TimeDuration, and it'll be very useful either way, but I'm wondering if there's a cleaner way to express what I want.

Going off of examples from pages like this, I tried the following in my groovy console in Intellij:

import groovy.time.TimeCategory
println ""
use(TimeCategory) {
    println "3.days.from.now = [${3.days.from.now}]"
}

If I call this right now, on Wed, Feb 01 at around 9:30 AM, This yields

3.days.from.now = [Sat Feb 04 00:00:00 EST 2017]

That's not exactly what I expected. Further experimentation shows that it's being fairly sensible - if you add a duration of a certain precision, like in days, it appears to drop less precise measures from the "now" that you're adding it to. If you add days or months, it drops the time. If you add hours, it uses the time:

1.month.from.now = [Wed Mar 01 00:00:00 EST 2017]
1.hour.from.now = [Wed Feb 01 10:18:42 EST 2017]

To get back to what I want, which is to add 3 days to this precise moment in time, I tried this:

import groovy.time.TimeCategory
println ""
use(TimeCategory) {
    now = new Date()
    println "now + 3.days = [${now + 3.days}]"
}

Which yields what I want!

now + 3.days = [Sat Feb 04 09:18:42 EST 2017]

But it's a little bit clunky, having to declare the Date first. After further experimentation I got a little better with this:

(3.days + 0.minutes).from.now = [Sat Feb 04 09:18:42 EST 2017]

So, I can roll with that if it's as good as it gets, but it feels like I could easily be missing a better way. Is there some clever way to specify that you want to add a month or a certain number of days, but with high precision? Or just a nicer way to do this in general? Thanks!

2 Answers 2

3

Are you open to using java.time?

groovy> import java.time.LocalDateTime 
groovy> def threeDays = LocalDateTime.now().plusDays(3) 

Result: 2017-02-04T16:07:19.352
1
  • I found that in the end, using java.time was just fine for my purposes. Also, it's unclear to me if there's a nice way to use TimeCategory without the use{} stuff - it sounded like you could call it statically but then it's no prettier than java.time. Thanks! Feb 7, 2017 at 17:42
2

For this exact problem, and this is working under the assumption that you actually just need to add three days and not do any other manipulation, the default groovy behavior for date arithmetic is enough:

$ groovysh
Groovy Shell (2.4.7, JVM: 1.7.0_79)
Type ':help' or ':h' for help.
-----------------------------------------------------------------------------------------------------------------------
groovy:000> x = new Date()
===> Wed Feb 01 22:01:17 CET 2017

groovy:000> x + 3
===> Sat Feb 04 22:01:17 CET 2017

groovy:000>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.