计算两个日期时间值之间的小时差 [英] Calculate difference in hours between two date time values

查看:190
本文介绍了计算两个日期时间值之间的小时差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个日期时间字符串 yyyy-MMM-dd hh:mm ,其值是 2016-JAN-17 12:23 ,我需要检查当前时间与该日期时间字符串之间的时差是否大于5小时。如果更大,则变量 is_greater 的值应等于1,否则应为0。

I have a date time string yyyy-MMM-dd hh:mm with the value 2016-JAN-17 12:23, and I need to check if the difference between current time and this date time string is greater than 5 hours. If it's greater, then the value of variable is_greater should be equal to 1, otherwise 0.

val datetimestring = "2016-JAN-17 12:23"
val formatter_datetime = new java.text.SimpleDateFormat("yyyy-MMM-dd hh:mm")
val parsed = formatter_datetime.parse(datetimestring)
val date = new java.sql.Date(parsed.getTime())
val now = Calendar.getInstance
val duration = now.getTime() - date.getTime()
val diffInHours = TimeUnit.MILLISECONDS.toHours(duration)
val is_greater: String = if (diffInHours<=5) "1" else "0"

我在 val duration = now.getTime()-date.getTime()行中遇到编译错误。它说无法解析符号-

P.S。我想避免使用任何外部库,例如jodatime。

P.S. I'd like to avoid using any external library like e.g. jodatime.

推荐答案

由于 getTime 方法返回<$ c的实例$ c> Date 类(而不是某些数值),您应该替换:

Since getTime method returns an instance of Date class (and not some numerical value), you should replace:

val duration = now.getTime() - date.getTime()

with:

val duration = now.getTimeInMillis() - date.getTimeInMillis()

这篇关于计算两个日期时间值之间的小时差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆