datetextgroovyformatrelative-time-span

How to subtract dates from each other


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.


Solution

  • 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