Scala conversion long to datetime

天涯浪子 提交于 2019-12-01 11:59:14

问题


I am using nscala-time (wrapper for Joda Time) and slick for a project. I'm trying to use this clause to write a line to the database:

Article.insert(0,"title1", "hellothere", DateTime.now.getMillis.asInstanceOf[Timestamp])

Apparently Slick does not support "dateTime" type defined in Joda Time, and I have to use java.sql.Timestamp instead. So I decide to do a little conversion inside the insert method, using "asInstanceOf". Unfortunately, Scala quickly tells me that Java.Long cannot be converted to Java.sql.Timestamp. Then I used this:

 val dateTime = new DateTime();
 val timeStamp = new Timestamp(dateTime.getMillis());

 Article.insert(0,"title1", "hellothere", timeStamp)

This magically works, and all I'm left with is confusion.

How can I convert it one way but not the other? Should I use a different conversion than asInstanceOf?


回答1:


You misunderstand what asInstanceOf does: asInstanceOf doesn't convert anything. What it does is lie to the compiler, telling it to believe something instead of going with the knowledge it has.

So, you had a Long, and then you got a Long, but pretended it was a Timestamp, which obviously doesn't work.

I have a simple recommendation regarding asInstanceOf: never use it.




回答2:


There's no magic about it. Your first statement:

DateTime.now.getMillis

is a Long. A Long is not a Timestamp, so it makes sense that you can't convert it to one by using asInstanceOf.

The second statement:

new Timestamp(dateTime.getMillis())

is using the Timestamp constructor to create a new Timestamp instance based on the dateTime.getMillis.



来源:https://stackoverflow.com/questions/20663662/scala-conversion-long-to-datetime

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