Scala中两个时间戳之间的秒数差异

时间:2017-11-28 10:16:14

标签: scala simpledateformat

所以我有这种格式的时间戳:

  

1990-10-31 18:43:12

我想计算其中两个时间戳之间的差异。

我的尝试:

val t1 = new java.text.SimpleDateFormat("yyyy-mm-dd HH:mm:ss")
val t2 = new java.text.SimpleDateFormat("yyyy-mm-dd HH:mm:ss")
t1.parse(timestamp1)
t2.parse(timestamp2)

但是我该怎么做?

1 个答案:

答案 0 :(得分:4)

首先,Java现在有java.time(JDK 1.8及更高版本)

import java.time._
import java.time.format._

然后(注意格式化程序/解析器现在是无状态的,重用它们总是安全的):

val p = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") //note months are MM

val t1 = LocalDateTime.parse(timestamp1, p)
val t2 = LocalDateTime.parse(timestamp2, p)

现在您有两个日期/时间,您需要转换为瞬间(实际上,ZonedDateTime,但它足以满足您的目的):

val i1 = t1.atZone(ZoneId.of("Europe/London"))
val i2 = t2.atZone(ZoneId.of("Europe/London"))

现在你有两个瞬间,你可以区分它们:

import java.time.temporal._
val diff = i1.until(i2, ChronoUnit.SECONDS) //Or MILLIS, MICROS etc

附录

这是REPL会议:

scala> :paste
// Entering paste mode (ctrl-D to finish)

val timestamp1 = "1990-10-31 18:43:12"
val timestamp2 = "1991-09-29 18:43:12"

import java.time._
import java.time.format._

val p = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") 

val t1 = LocalDateTime.parse(timestamp1, p) 
val t2 = LocalDateTime.parse(timestamp2, p)

val i1 = t1.atZone(ZoneId.of("Europe/London"))
val i2 = t2.atZone(ZoneId.of("Europe/London"))

import java.time.temporal._
val diff = i1.until(i2, ChronoUnit.SECONDS)

以下是结果:

// Exiting paste mode, now interpreting.

timestamp1: String = 1990-10-31 18:43:12
timestamp2: String = 1991-09-29 18:43:12
import java.time._
import java.time.format._
p: java.time.format.DateTimeFormatter = Value(YearOfEra,4,19,EXCEEDS_PAD)'-'Value(MonthOfYear,2)'-'Value(DayOfMonth,2)' 'Value(HourOfDay,2)':'Value(MinuteOfHour,2)':'Value(SecondOfMinute,2)
t1: java.time.LocalDateTime = 1990-10-31T18:43:12
t2: java.time.LocalDateTime = 1991-09-29T18:43:12
i1: java.time.ZonedDateTime = 1990-10-31T18:43:12Z[Europe/London]
i2: java.time.ZonedDateTime = 1991-09-29T18:43:12+01:00[Europe/London]
import java.time.temporal._
diff: Long = 28767600