Convert seconds since epoch to joda DateTime in Scala

£可爱£侵袭症+ 提交于 2019-12-18 19:07:24

问题


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> 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

回答1:


Check a quick REPL session:

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(long instant)

Still don't get it? Let's try a slightly different version:

scala> 1378607203L * 1000
res8: Long = 1378607203000

Notice the L indicating a literal of type Long. You are asking for 1 trillion! And Int only go as far as 2 billons:

scala> Int.MaxValue
res7: Int = 2147483647

So doing DateTime(1378607203L*1000) will make it work.



来源:https://stackoverflow.com/questions/18680398/convert-seconds-since-epoch-to-joda-datetime-in-scala

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!