35

I want to add hours or minutes to a current date. For example I create a Date object with current time and date, and I want to increment it by 30min, how can I do such thing in Grails/Groovy ?

Date Now : Thu Jan 16 11:05:48 EST 2014
Adding 30min to Now : Thu Jan 16 11:35:48 EST 2014

I was wondering if I could do the same that we can do with add 1 to date and it moves it a day ahead.

tim_yates
  • 167,322
  • 27
  • 342
  • 338
AlexCon
  • 1,127
  • 1
  • 13
  • 31
  • Similar: https://stackoverflow.com/questions/25046910/how-do-i-subtract-minutes-from-current-time – biniam Aug 31 '17 at 13:17

3 Answers3

70

You can use TimeCategory

import groovy.time.TimeCategory

currentDate =  new Date()

println currentDate

use( TimeCategory ) {
    after30Mins = currentDate + 30.minutes
}

println after30Mins
tim_yates
  • 167,322
  • 27
  • 342
  • 338
Rami Enbashi
  • 3,526
  • 1
  • 19
  • 21
  • Link to the groovy API doc: http://docs.groovy-lang.org/latest/html/api/groovy/time/TimeCategory.html – RMorrisey Apr 02 '15 at 22:03
  • Gives out an exception like this: `groovy.lang.MissingPropertyException: No such property: hours for class: java.lang.Integer [See nested exception: groovy.lang.MissingPropertyException: No such property: hours for class: java.lang.Integer]` – Prakhar Mishra Aug 11 '22 at 10:12
3

If your goal is very simple, you can just manipulate the underlying millisecond value.

final Long HOUR = 60 * 60 * 1000 // milliseconds in an hour
​Date now = new Date()
Date oneHourAgo = new Date(now.toInstant().toEpochMilli()​ - HOUR)
Aaron Scherbing
  • 507
  • 6
  • 6
0

Just use the java.time package.

import java.time.LocalDateTime

Date now = new Date()
Date thirtyMinsFromNow = LocalDateTime.now().plusMinutes(30).toDate()

println "Date Now: $now"
println "Adding 30min to Now: $thirtyMinsFromNow"
SGT Grumpy Pants
  • 4,118
  • 4
  • 42
  • 64