11

In Scala, I am converting Date to Timestamp. I am currently doing this with:

val date = new java.util.Date()
new java.sql.Timestamp(new org.joda.time.DateTime(date).getMillis)

Is there a slicker way of doing this? Java-informed responses would also be relevant.

Philippe
  • 9,582
  • 4
  • 39
  • 59
will
  • 111
  • 1
  • 1
  • 7

2 Answers2

16

Why not something as simple as using Date.getTime()?

new java.sql.Timestamp(date.getTime)

You don't need Joda time for this. Scala isn't really relevant here, unless you need an implicit conversion:

//import once, use everywhere
implicit def date2timestamp(date: java.util.Date) = 
    new java.sql.Timestamp(date.getTime)

val date = new java.util.Date

//conversion happens implicitly
val timestamp: java.sql.Timestamp = date
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
13

If you don't want to even construct a Date object you could simply use this:

new java.sql.Timestamp(System.currentTimeMillis())

I would think this would be a tiny bit more efficient than using a new Date(). But if you already have a date object you want to get the date from this will work for you.

new java.sql.Timestamp(data.getTime())
myyk
  • 1,537
  • 1
  • 15
  • 35