如何在 Scala 中将 Long 转换为 Int?
我想使用以下函数将 Joda 时间转换为 Unix 时间戳:
def toUnixTimeStamp(dt : DateTime) : Int = {
val millis = dt.getMillis
val seconds = if(millis % 1000 == 0) millis / 1000
else { throw new IllegalArgumentException ("Too precise timestamp") }
if (seconds > 2147483647) {
throw new IllegalArgumentException ("Timestamp out of range")
}
seconds
}
我想要获取的时间值永远不会达到毫秒精度,它们是约定的秒精度 UTC,并且将进一步存储(在MySQL DB)作为 Int,标准 Unix 时间戳是我们公司时间记录的标准。但 Joda Time 只提供 getMillis 而不是 getSeconds,所以我必须获取一个 Long 毫秒级精确时间戳并将其除以 1000 以生成标准 Unix 时间戳。
我一直在让 Scala 从 Long 值中生成 Int 。怎样做这样的演员?
I'd like to use the folowing function to convert from Joda Time to Unix timestamp:
def toUnixTimeStamp(dt : DateTime) : Int = {
val millis = dt.getMillis
val seconds = if(millis % 1000 == 0) millis / 1000
else { throw new IllegalArgumentException ("Too precise timestamp") }
if (seconds > 2147483647) {
throw new IllegalArgumentException ("Timestamp out of range")
}
seconds
}
Time values I intend to get are never expected to be millisecond-precise, they are second-precise UTC by contract and are to be further stored (in a MySQL DB) as Int, standard Unix timestamps are our company standard for time records. But Joda Time only provides getMillis and not getSeconds, so I have to get a Long millisecond-precise timestamp and divide it by 1000 to produce a standard Unix timestamp.
And I am stuck making Scala to make an Int out of a Long value. How to do such a cast?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对 Long 使用
.toInt
方法,即seconds.toInt
Use the
.toInt
method on Long, i.e.seconds.toInt