[英]Convert Date to Timestamp in Scala
In Scala, I am converting Date to Timestamp. 在Scala中,我将Date转换为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.
Java知情的回复也是相关的。
Why not something as simple as using Date.getTime()
? 为什么不像使用
Date.getTime()
那么简单?
new java.sql.Timestamp(date.getTime)
You don't need Joda time for this. 你不需要Joda时间。 Scala isn't really relevant here, unless you need an implicit conversion:
除非您需要隐式转换,否则Scala在这里并不重要:
//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
If you don't want to even construct a Date object you could simply use this: 如果您不想甚至构造Date对象,您可以简单地使用它:
new java.sql.Timestamp(System.currentTimeMillis())
I would think this would be a tiny bit more efficient than using a new Date(). 我认为这比使用新的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())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.