我是Java的新手。我已经编写了此函数,以查找从当前时间到函数参数中时间的小时差。结果有点复杂,我该如何改善呢?谢谢。
private int getTimeDiffFromCurrent(String date, String time)
{
String str_date_time = date + " " + time;
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.getDefault());
try {
Date date_time = (Date) formatter.parse(str_date_time);
int hr = (int)((System.currentTimeMillis() - date_time.getTime())/(1000 * 60 * 60));
return hr>=0? hr : 1000;
}
catch (Exception e) {
System.out.println(e.toString() + ", " + str_date_time);
}
return 1000;
}
用例示例:
getTimeDiffFromCurrent("19/07/2020", "07:19:00");
答案 0 :(得分:3)
如果您使用java.time
软件包中提供的Java Date and Time API,那么它将变得更加简单。
static long getDifferenceInHours(ZonedDateTime dateTime) {
ZonedDateTime now = ZonedDateTime.now();
return Duration
.between(dateTime, now)
.toHours();
}
然后您可以这样称呼它:
ZonedDateTime zdt = ZonedDateTime.of(2020, 7, 16, 0, 0, 0, 0, ZoneId.systemDefault());
long difference = getDifferenceInHours(zdt);
System.out.println(difference);
您不应使用数学来计算日期和时间差;有很多API可以很好地完成这项工作。
我在上述代码中使用了ZonedDateTime
,因为这考虑了可能的DST更改。例如,在欧洲/阿姆斯特丹时区,由于壁钟在两点跳了一个小时,因此在2020年3月29日之间,00:00和05:00仅为4小时(而不是5小时)。