[英]Java how to compare LocalTime using only hours, minutes and seconds
I want to compare if 2 LocalTime
are equal, but only using the hours, minutes and seconds, not with all the data of the variable, like milliseconds. 我想比较2
LocalTime
是否相等,但仅使用小时,分钟和秒,而不使用变量的所有数据(例如毫秒)进行比较。
How can I accomplish that? 我该怎么做?
You can set the hours to the same in both with myTime.withHour(0)
, than you have left only the minutes and seconds that differ and you are able to come these 2 times. 您可以使用
myTime.withHour(0)
将小时设置为相同,而不是只剩下不同的分钟和秒,并且您可以使用这两次。
Example: 例:
time1 = ...
time2 = ...
if (time1.withHour(0).equals(time2.withHour(0))) {
System.out.println('Minutes and Seconds of time1 and time2 are equal!');
}
You can just set both nanos to one number to make them the same with each other, say, zero, to compare them. 您可以将两个nanos都设置为一个数字,以使它们彼此相同(例如为零)以进行比较。
LocalTime localTime1 = LocalTime.of(1, 2, 3, 100);
LocalTime localTime2 = LocalTime.of(1, 2, 3, 47);
if (localTime1.withNano(0).equals(localTime2.withNano(0))){
System.out.println("something");
}
Considering the last edited version of your question, you can compare two instances of LocalTime
by just hour, minute and second part this way: 考虑到问题的最后编辑版本,您可以通过以下方式仅比较小时,分钟和第二部分来比较
LocalTime
的两个实例:
LocalTime lt1 = LocalTime.now(); // usually contains seconds and subseconds
LocalTime lt2 = LocalTime.of(22, 48); // example with zero second part
boolean isEqualInSecondPrecision =
lt1.truncatedTo(ChronoUnit.SECONDS).equals(lt2.truncatedTo(ChronoUnit.SECONDS));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.