1

I'm new to groovy and currently working on manipulating dates. Is their anyway that I can subtract or add two dates in groovy? For example I have:

def build = Build.get(params.id)
def firstDate = build.firstDate
def secondDate = build.secondDate

now I want to add the dates something like:

firstDate + secondDate = (total hours or minutes) 

....or does it need to be converted to something like integer?

Update:

For example, the start date is Jan.7,2013 12:00 and the end date is Jan.8,2013 1:30. I want to calculate how many hours or minute their is in between those dates...sorry for my bad english :(

tim_yates
  • 167,322
  • 27
  • 342
  • 338
noob
  • 300
  • 5
  • 16

4 Answers4

3

For example, the start date is Jan.7,2013 12:00 and the end date is Jan.8,2013 1:30. I want to calculate how many hours or minute their is in between those dates.

The following will give difference in milliseconds.

def diffdate = secondDate.getTime() - firstDate.getTime();

Now use appropriate math to convert to hours and minutes.

e.g. diffdate / 60000 will give you minutes, diffdate / 3600000 will give you hours

xagyg
  • 9,562
  • 2
  • 32
  • 29
2

Using TimeCategory:

use (groovy.time.TimeCategory) {
   def duration = secondDate - firstDate
   println "Days: ${duration.days}, Hours: ${duration.hours}, Hours: ${duration.minutes}"
}
Reimeus
  • 158,255
  • 15
  • 216
  • 276
1

The TimeCategory category provides exactly what you're looking for :)

When using this category, java.util.Dates become much more user-friendly and let you do the things you'd expect them to do with very little code. For example, subtracting two dates and getting a TimeDuration as a result:

import groovy.time.TimeCategory

// Using same dates as the question's example.
def start = Date.parseToStringDate('Mon Jan 07 12:00:00 GMT 2013')
def end = Date.parseToStringDate('Tue Jan 07 01:30:00 GMT 2013')

use (TimeCategory) {
    println start - end // Prints "10 hours, 30 minutes"
}
epidemian
  • 18,817
  • 3
  • 62
  • 71
0

I'm going to make an assumption here: Groovy can use Java Libraries.

That being the case, you should look into the JodaTime library. It has a class named Duration. The duration can take two DateTime classes. They are very similar to java Date's. Here's how you can print out a duration in a pretty way. I'll inline the answer in the link for convenience:

Duration duration = new Duration(123456); // in milliseconds
PeriodFormatter formatter = new PeriodFormatterBuilder()
     .appendDays()
     .appendSuffix("d")
     .appendHours()
     .appendSuffix("h")
     .appendMinutes()
     .appendSuffix("m")
     .appendSeconds()
     .appendSuffix("s")
     .toFormatter();
String formatted = formatter.print(duration.toPeriod());
System.out.println(formatted);
Community
  • 1
  • 1
Daniel Kaplan
  • 62,768
  • 50
  • 234
  • 356