Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert seconds since epoch to joda DateTime in Scala

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
like image 960
randombits Avatar asked Sep 08 '13 04:09

randombits


1 Answers

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.

like image 58
pedrofurla Avatar answered Sep 28 '22 06:09

pedrofurla