如何从时间戳转换为 com.websudos.phantom.dsl.DateTime 或设置当前时间
How to convert from Timestamp to com.websudos.phantom.dsl.DateTime or set the current time
我正在使用 phantom 1.29.4 和 scala 2.11.8,尝试用 scala 动手操作 cassandra。我的数据模型如下所示...
case class User(id: Long, name: String, createdDate: Timestamp, ...)
class UserTableMapping extends CassandraTable[UserTableDao, User] {
...
object createdDate extends DateTimeColumn(this)
...
}
abstract class UserTableDao extends UserTableMapping with RootConnector {
def createUser(user: User) = insert.value...(_.createdDate, user.createdDate)
...
}
现在,我收到类型不匹配错误("expected com.websudos.phantom.dsl.DateTime actual java.sql.Timestamp",这很明显)...现在我的问题是如何将 Timestamp 转换为 DateTime(因为,我的服务层在不同的子项目中而且我不想在那里添加所有幻影 dsl 罐子)或向 Datetime 提供当前时间?
我也试过提供如下所示的隐式转换...
implicit def sqlTimestampToPhantomDateTime(dt: Timestamp): DateTime = new DateTime(dt)
但还是没有运气...
请帮助我,因为我是 cassandra 的新手...谢谢...
那只是一个 joda DateTime:
type DateTime = org.joda.time.DateTime
joda DateTime 有一个 millisecond constructor,所以你快到了。您需要做的就是从您的 Timestamp
实例中获取以毫秒为单位的时间戳,并使用它来构建一个 DateTime
实例:
new DateTime(timestampInstance.getTime, DateTimeZone.UTC)
但是,您也可以只创建一个新的 DateTime 实例以获取当前时间:
new DateTime(DateTimeZone.UTC)
编辑:对于以后阅读本文的任何人,@flavian 在 phantom 如何处理时区方面提出了一个有效的观点,我编辑了这个以反映它。
另一个答案是正确的,说 phantom 默认只使用 Joda Time,但它引入了一个相当危险的建议,即使用 new DateTime()
空参数构造函数,它将使用机器的本地时区它正在执行。
默认情况下,phantom 在从 Cassandra 解析回来时强制执行 DateTimeZone.UTC
,因为 Cassandra 只处理 timestamp
类型的 UTC 时间。
所以你必须使用 new Datetime(time, DateTimeZone.UTC)
来确保你从 Cassandra 得到的东西和你输入的东西一样。
我正在使用 phantom 1.29.4 和 scala 2.11.8,尝试用 scala 动手操作 cassandra。我的数据模型如下所示...
case class User(id: Long, name: String, createdDate: Timestamp, ...)
class UserTableMapping extends CassandraTable[UserTableDao, User] {
...
object createdDate extends DateTimeColumn(this)
...
}
abstract class UserTableDao extends UserTableMapping with RootConnector {
def createUser(user: User) = insert.value...(_.createdDate, user.createdDate)
...
}
现在,我收到类型不匹配错误("expected com.websudos.phantom.dsl.DateTime actual java.sql.Timestamp",这很明显)...现在我的问题是如何将 Timestamp 转换为 DateTime(因为,我的服务层在不同的子项目中而且我不想在那里添加所有幻影 dsl 罐子)或向 Datetime 提供当前时间?
我也试过提供如下所示的隐式转换...
implicit def sqlTimestampToPhantomDateTime(dt: Timestamp): DateTime = new DateTime(dt)
但还是没有运气...
请帮助我,因为我是 cassandra 的新手...谢谢...
那只是一个 joda DateTime:
type DateTime = org.joda.time.DateTime
joda DateTime 有一个 millisecond constructor,所以你快到了。您需要做的就是从您的 Timestamp
实例中获取以毫秒为单位的时间戳,并使用它来构建一个 DateTime
实例:
new DateTime(timestampInstance.getTime, DateTimeZone.UTC)
但是,您也可以只创建一个新的 DateTime 实例以获取当前时间:
new DateTime(DateTimeZone.UTC)
编辑:对于以后阅读本文的任何人,@flavian 在 phantom 如何处理时区方面提出了一个有效的观点,我编辑了这个以反映它。
另一个答案是正确的,说 phantom 默认只使用 Joda Time,但它引入了一个相当危险的建议,即使用 new DateTime()
空参数构造函数,它将使用机器的本地时区它正在执行。
默认情况下,phantom 在从 Cassandra 解析回来时强制执行 DateTimeZone.UTC
,因为 Cassandra 只处理 timestamp
类型的 UTC 时间。
所以你必须使用 new Datetime(time, DateTimeZone.UTC)
来确保你从 Cassandra 得到的东西和你输入的东西一样。