[英]Calculate time difference between two times represented as longs
I am trying to calculate the difference between two times, which are represented as longs in the Format HHmm 24 hour time. 我正在尝试计算两次之间的差异,在24小时制HHmm格式中用long表示。 Eg 4:30pm is represented by the long 0430.
例如,下午4:30表示较长的0430。
I am happy for the difference to be in minutes. 我很高兴能在几分钟之内实现差异。
Is there a simple calculation that can be done to achieve this? 有没有简单的计算可以做到这一点? I am aware of Java's Date class, however I want to avoid having to store dummy date information just for a calculation on time.
我知道Java的Date类,但是我想避免只为按时计算而存储伪日期信息。
Thanks! 谢谢!
Putting aside the fact that this is a really, really bad way to store times, the easiest way to do this is to convert the HHMM time to minutes since the start of the day: 撇开这是存储时间的一种非常非常糟糕的事实,最简单的方法是将HHMM时间转换为从一天开始以来的分钟数:
long strangeTimeFormatToMinutes(long time) {
long minutes = time % 100;
long hours = time / 100;
return minutes + 60 * hours;
}
Then just use plain old subtraction to get the difference. 然后,只需使用普通的旧减法即可得出差值。
You may also want to add validation that minutes
and hours
are in the ranges you expect, ie 0-59 and 0-23. 您可能还需要添加验证,以确保
minutes
和hours
处于您期望的范围内,即0-59和0-23。
You mentioned that you didn't want to use the Date class because it required you to use a dummy date. 您提到您不想使用Date类,因为它要求您使用虚拟日期。 The LocalTime class does not require that.
LocalTime类不需要。
LocalTime start = LocalTime.of(6,15,30,200); // h, m, s, nanosecs
LocalTime end = LocalTime.of(6,30,30,320);
Duration d = Duration.between(start, end);
System.out.println(d.getSeconds()/60);
First convert your integer to a 4-character string, padding with leading zeros. 首先将整数转换为4个字符的字符串,并以前导零填充。
For example, 430
becomes 0430
and parsed as 04:30
. 例如,
430
变为0430
并被解析为04:30
。 Or, 15
becomes 0015
and parsed as quarter past midnight, 00:15
. 或者,
15
变为0015
并解析为午夜00:15
四分之一。
String input = String.format( "%04d", yourTimeAsInteger );
LocalDate
The LocalTime
class represents a time-of-day value with no date and no time zone. LocalTime
类表示没有日期和时区的一天中的时间值。
DateTimeFormatter f = DateTimeFormatter.ofPattern( "HHmm" );
LocalTime ld = LocalTime.parse( input , f ) ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.