James Martineau James Martineau - 1 year ago 163
Groovy Question

Groovy TimeCategory - Is there a better way to manipulate times/durations than this?

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!

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download