Scala/Java date FAQ: How do I create a Scala Date from a Long value? When I give the Java Date class constructor a Long value it returns a date from 1970.
Solution
You need to multiply the Long value by 1000, and also make sure you pass a Long value into the Date constructor. The Scala REPL shows how this works:
scala> import java.util._
import java.util._
# WRONG: 1970?
scala> val d = new Date(1513714678)
d: java.util.Date = Sun Jan 18 05:28:34 MST 1970
# WRONG: multiply by 1000 and it’s still 1970?
scala> val d = new Date(1513714678 * 1000)
d: java.util.Date = Thu Jan 22 12:56:29 MST 1970
# SOLUTION: multiply by 1000 and make sure you pass in a Long
scala> val d = new Date(1513714678 * 1000L)
d: java.util.Date = Tue Dec 19 13:17:58 MST 2017
The reason you need to do these two things are:
- The Java Date constructor expects the time to be in milliseconds, not seconds
- The
Dateconstructor expects aLongvalue
In the second case I haven’t looked into the Date source code to see why an integer causes such a problem with the Date constructor. All I can say at this time is that passing an Integer/Int value into the Date constructor clearly causes a problem.
On a personal note, I ran into this problem when working with a MySQL database for a Drupal website. Drupal is written in PHP, and PHP dates are stored as a
Longvalue, as shown in my1513714678example.
Example Long-to-Date functions
While I’m in the neighborhood, here are two “Long to Date” functions that I created in that Scala/Drupal app:
import java.text.SimpleDateFormat
import java.util.Date
object DateUtils {
def formatDateForBlogPages(date: Long): String = {
val d = new Date(date * 1000L)
new SimpleDateFormat("LLLL d, yyyy").format(d)
}
def formatDateForSitemap(date: Long): String = {
val d = new Date(date * 1000L)
new SimpleDateFormat("yyyy-MM-d").format(d)
}
}
In summary, if you wanted to see how to create a Scala Date from a Long value, I hope this example is helpful.
| this post is sponsored by my books: | |||
#1 New Release |
FP Best Seller |
Learn Scala 3 |
Learn FP Fast |