如何减少日期 [英] How to subtract dates from each other

查看:136
本文介绍了如何减少日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Groovy。我已经解析了一个文本文件,其行包含信息,包括日期。我现在只有日期,例如:

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

我想比较这些值之间的三角洲;我该怎么办?即,我想从第二个减去第一个,并将该值与第三个和第二个之间的差值进行比较。我将保存最大的值。

解决方案

假设你的时间在一个文件 times.txt ,你可以这样做:

  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 )
deltas<<< nextDate - prevDate
prevDate = nextDate
}
}
}
}
println deltas
println(deltas.max {it.toMilliseconds( )})

哪些将打印:

  [1小时19分钟25.981秒1小时11分钟5.051秒] 
1小时19分钟25.981秒


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

这篇关于如何减少日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆