将自纪元以来的秒数转换为 Scala 中的 joda DateTime
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18680398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert seconds since epoch to joda DateTime in Scala
提问by randombits
I am attempting to take seconds since epoch and turn it into a DateTime object in Scala. I am use joda. Unfortunately whether I use seconds or milliseconds, I'm getting weird results. What am I doing wrong here?
我试图从纪元开始花几秒钟的时间并将其转换为 Scala 中的 DateTime 对象。我正在使用乔达。不幸的是,无论我使用秒还是毫秒,我都会得到奇怪的结果。我在这里做错了什么?
scala> new org.joda.time.DateTime(1378607203*1000)
res2: org.joda.time.DateTime = 1969-12-31T02:31:40.984Z
scala> new org.joda.time.DateTime(1378607203)
res3: org.joda.time.DateTime = 1970-01-16T22:56:47.203Z
回答by pedrofurla
Check a quick REPL session:
检查快速 REPL 会话:
scala> 1378607203 * 1000
res6: Int = -77299016
Odd, isn't it? :) Can you guess why this is happening?
很奇怪,不是吗?:) 你能猜出为什么会这样吗?
I will give you a hint extracted from DateTime's constructor you are trying to use.
我会给你一个从DateTime你试图使用的构造函数中提取的提示。
DateTime(long instant)
Still don't get it? Let's try a slightly different version:
还是不明白?让我们尝试一个稍微不同的版本:
scala> 1378607203L * 1000
res8: Long = 1378607203000
Notice the Lindicating a literal of type Long. You are asking for 1 trillion! And Int only go as far as 2 billons:
请注意L指示 Long 类型的文字。你要1万亿!而 Int 最多只能达到 20 亿:
scala> Int.MaxValue
res7: Int = 2147483647
So doing DateTime(1378607203L*1000)will make it work.
所以这样做DateTime(1378607203L*1000)会让它起作用。

