سؤال

I am using Groovy. I have parsed a textfile whose lines contain information, including dates. I now have just the dates, for example:

08:13:16,121
09:32:42,102
10:43:47,153

I want to compare the deltas between these values; how can I do this? i.e, I want to subtract the first from the second, and compare that value to the difference between the third and the second. I will save the largest value.

هل كانت مفيدة؟

المحلول

Assuming your times are in a file times.txt, you can do this:

def parseDate = { str -> new Date().parse( 'H:m:s,S', str ) }

def prevDate = null
def deltas = []

use( groovy.time.TimeCategory ) {
  new File( 'times.txt' ).eachLine { line ->
    if( line ) {
      if( !prevDate ) {
        prevDate = parseDate( line )
      }
      else {
        def nextDate = parseDate( line )
        deltas << nextDate - prevDate
        prevDate = nextDate
      }
    }
  }
}
println deltas
println( deltas.max { it.toMilliseconds() } )

Which will print:

[1 hours, 19 minutes, 25.981 seconds, 1 hours, 11 minutes, 5.051 seconds]
1 hours, 19 minutes, 25.981 seconds

نصائح أخرى

You can use TimeCategory to add methods for time differences to date classes:

import groovy.time.TimeCategory

use(TimeCategory) {
    println date1 - date2
}

Subtracting one date from another will result in a TimeDuration object.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top