从scala中的DateTime中减去DateTime

jxs*_*ord 6 scala jodatime

我对scala和jodatime都比较陌生,但两者都给人留下了深刻的印象.我想弄清楚是否有更优雅的方法来做一些日期算术.这是一个方法:


private def calcDuration() : String = {
  val p = new Period(calcCloseTime.toInstant.getMillis - calcOpenTime.toInstant.getMillis)
  val s : String = p.getHours.toString + ":" + p.getMinutes.toString + 
      ":" + p.getSeconds.toString
  return s
}
Run Code Online (Sandbox Code Playgroud)

我将所有内容转换为字符串,因为我将它放入MongoDB,我不知道如何序列化joda持续时间或句点.如果有人知道我真的很感激答案.

无论如何,calcCloseTime和calcOpenTime方法返回DateTime对象.将它们转换为Instants是我发现的最好的方法.有没有更好的办法?

另一个问题:当小时,分钟或秒是单个数字时,结果字符串不是零填充.是否有一种简单的方法使字符串看起来像HH:MM:SS?

谢谢,约翰

Arj*_*ijl 8

Period格式化由PeriodFormatter类完成.您可以使用默认值,也可以使用PeriodFormatterBuilder构建自己的默认值.您可能需要更多代码,因为您可能需要正确设置此构建器,但您可以使用它,例如:


scala> import org.joda.time._
import org.joda.time._

scala> import org.joda.time.format._
import org.joda.time.format._

scala> val d1 = new DateTime(2010,1,1,10,5,1,0)
d1: org.joda.time.DateTime = 2010-01-01T10:05:01.000+01:00

scala> val d2 = new DateTime(2010,1,1,13,7,2,0)
d2: org.joda.time.DateTime = 2010-01-01T13:07:02.000+01:00

scala> val p = new Period(d1, d2)
p: org.joda.time.Period = PT3H2M1S

scala> val hms = new PeriodFormatterBuilder() minimumPrintedDigits(2) printZeroAlways() appendHours() appendSeparator(":") appendMinutes() appendSuffix(":") appendSeconds() toFormatter
hms: org.joda.time.format.PeriodFormatter = org.joda.time.format.PeriodFormatter@4d2125

scala> hms print p
res0: java.lang.String = 03:02:01
Run Code Online (Sandbox Code Playgroud)

您或许也应该意识到不考虑日期转换:


scala> val p2 = new Period(new LocalDate(2010,1,1), new LocalDate(2010,1,2))
p2: org.joda.time.Period = P1D

scala> hms print p2                                                         
res1: java.lang.String = 00:00:00
Run Code Online (Sandbox Code Playgroud)

因此,如果您还需要对这些内容进行处理,您还需要将所需的字段(天,周,年)添加到格式化程序中.


Jon*_*ffe 7

你可能想看一下Jorge Ortiz的Joda-Time包装器,scala-time用于在Scala中使用更好的东西.

然后你应该可以使用类似的东西

(calcOpenTime to calcCloseTime).millis
Run Code Online (Sandbox Code Playgroud)