长整数和nscala_时间

长整数和nscala_时间,scala,datetime,type-conversion,long-integer,Scala,Datetime,Type Conversion,Long Integer,我的首要问题是将从流中获得的一些时间值作为64位纳秒Unix时间,在Scala中,使用需要毫秒的nscala_时间应该很容易。遇到一些问题后,我开始试验,发现它很容易将Long转换为Int,我不理解这方面的规则。得到一个可以传递给nscala_time的数字后,我发现我选择的数字没有转换为有效的日期时间字符串 我的代码如下: val constructedTimeOne:Long = (((((((3) * 24) + 12) * 60) + 34) * 60 + 56) * 1000)

我的首要问题是将从流中获得的一些时间值作为64位纳秒Unix时间,在Scala中,使用需要毫秒的nscala_时间应该很容易。遇到一些问题后,我开始试验,发现它很容易将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
有人能解释一下保持价值长期不变的规则吗?我可以将asInstanceOf移到第三节中的任何乘法项上,它可以正常工作,但是将它放在括号表达式的外侧,就像第二节中一样,是不起作用的


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

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

出现1970-02-35的原因是日期格式错误。每月的某一天使用d而不是大写,这表示一年中的某一天。文档是

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

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

现在,对于长值的使用,您应该使用toLong,而不是使用instanceof强制转换类。当使用文字时,使用5L或5L格式表示一个长的数字。

谢谢-使用1000000L作为从纳秒到毫秒的转换因子足以解决原始问题。