长整数,和 nscala_time

long integers, and nscala_time

我的首要问题是在 Scala 中使用 nscala_time(需要毫秒 --- 应该足够简单).遇到一些问题后,我开始试验,发现它很容易将 Long 转换为 Int,但我无法理解其中的规则。得到一个可以传递给 nscala_time 的数字后,我发现我选择的数字没有转换为有效的日期时间字符串。

我的代码如下:

  val constructedTimeOne:Long = (((((((3) * 24) + 12) * 60) + 34) * 60 + 56) * 1000)
  val constructedDateOne = new DateTime(constructedTimeOne)
  val constructedStringOne = constructedDateOne.toString("YYYY-MM-DD HH:MM:SS")
  println(s"constructedTime $constructedTimeOne converts to $constructedStringOne")

  val constructedTimeTwo:Long = constructedTimeOne + (31 * 24 * 60 * 60 * 1000).asInstanceOf[Long]
  val constructedDateTwo = new DateTime(constructedTimeTwo)
  val constructedStringTwo = constructedDateTwo.toString("YYYY-MM-DD HH:MM:SS")
  println(s"constructedTime $constructedTimeTwo converts to $constructedStringTwo")

  val constructedTimeThree:Long = (constructedTimeOne + (31.asInstanceOf[Long] * 24 * 60 * 60 * 1000 ))
  val constructedDateThree = new DateTime(constructedTimeThree)
  val constructedStringThree = constructedDateThree.toString("YYYY-MM-DD HH:MM:SS")
  println(s"constructedTime $constructedTimeThree converts to $constructedStringThree")

当我 运行 它时,我得到这个输出:

constructedTime 304496000 converts to 1970-01-04 13:01:00
constructedTime -1312071296 converts to 1969-12-350 20:12:70
constructedTime 2982896000 converts to 1970-02-35 13:02:00

有人可以解释一下保持值 Long 的规则吗?我可以将 "asInstanceOf" 移动到第三部分中的任何乘法项,它工作正常,但将它放在括号表达式的外部(如第二部分)不起作用。

而且,当然,将任意数字(在本例中为时间间隔,毫秒)转换为日期和时间的结果应该会产生有效的日期和时间,所以我做错了什么产生了日期 1970 -02-35?

您的代码可能存在两个主要问题。

1970-02-35 的原因是您错误地设置了日期格式。一个月中的第几天使用 d 而不是大写 D,这是 "day of the year"。文档是 here.

因此,如果您将其更改为:

constructedDateThree.toString("YYYY-MM-dd HH:MM:SS")

它将按预期工作:

scala> val constructedStringThree = constructedDateThree.toString("YYYY-MM-dd HH:MM:SS")
constructedStringThree: String = 1970-02-04 09:02:00

现在,要使用 Long 值,您应该使用 toLong 而不是仅使用 asInstanceOf 转换 class。当使用文字时,使用格式 5L5l 来表示一个 Long 数字。