How to subtract dates from each other

I am using Groovy. I analyzed a text file whose lines contain information, including dates. Now I only have dates, for example:

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

I want to compare the delta between these values; How can i do this? those. I want to subtract the first from the second and compare this value with the difference between the third and second. I will retain the greatest value.

+1
source share
2 answers

Assuming your time is in the times.txt file, 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() } ) 

What will print:

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

You can use TimeCategory to add time difference methods to date classes:

 import groovy.time.TimeCategory use(TimeCategory) { println date1 - date2 } 

Subtracting one date from another, you get a TimeDuration object.

+5
source

Source: https://habr.com/ru/post/1380749/


All Articles