How to subtract dates from each other

不打扰是莪最后的温柔 提交于 2019-12-24 13:15:11

问题


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.


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/8085482/how-to-subtract-dates-from-each-other

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!