在 Java 中计算时间,例如。 1900-1710 = 110 分钟
Compute times in Java eg. 1900-1710 = 110 mins
java 有什么方法可以做到这一点吗?我想让它像那样计算时间。 0950-0900 是 50 分钟,但 1700-1610 = 50 分钟而不是 90,1900-1710 = 110 而不是 190。谢谢 :)
看看在 Java SE 8 中介绍的 Duration (part of the new Date & Time API。
例如。 (未经测试):
long minutes = Duration.between(toLocalTime(1710), toLocalTime(1900)).toMinutes();
private LocalTime toLocalTime(int time){
return LocalTime.of(time / 100, time % 100);
}
您可以使用 Java 8.
中的新 Java 日期 API
LocalTime start = LocalTime.parse("19:00");
LocalTime end = LocalTime.parse("17:10");
Duration elapsed = Duration.between(start, end);
System.out.println(elapsed.toMinutes());
如果切换开始和结束,这将输出:-110 和 110。
如果您只有整数,并且不关心验证,您可以完成所有操作而根本不涉及时间部分:
public int getMinutesBetween(int time1, int time2) {
// Extract hours and minutes from compound values, which are base-100,
// effectively.
int hours1 = time1 / 100;
int hours2 = time2 / 100;
int minutes1 = time1 % 100;
int minutes2 = time2 % 100;
// Now we can perform the arithmetic based on 60-minute hours as normal.
return (hours2 - hours1) * 60 + (minutes2 - minutes1);
}
但是,我强烈建议您使用更合适的表示 - 这些不只是正常的int
值...它们实际上是 "time of day" 值,因此 LocalTime
(在 Joda Time 或 Java 8 的 java.time
中)是最合适的表示形式,IMO。
java 有什么方法可以做到这一点吗?我想让它像那样计算时间。 0950-0900 是 50 分钟,但 1700-1610 = 50 分钟而不是 90,1900-1710 = 110 而不是 190。谢谢 :)
看看在 Java SE 8 中介绍的 Duration (part of the new Date & Time API。
例如。 (未经测试):
long minutes = Duration.between(toLocalTime(1710), toLocalTime(1900)).toMinutes();
private LocalTime toLocalTime(int time){
return LocalTime.of(time / 100, time % 100);
}
您可以使用 Java 8.
中的新 Java 日期 APILocalTime start = LocalTime.parse("19:00");
LocalTime end = LocalTime.parse("17:10");
Duration elapsed = Duration.between(start, end);
System.out.println(elapsed.toMinutes());
如果切换开始和结束,这将输出:-110 和 110。
如果您只有整数,并且不关心验证,您可以完成所有操作而根本不涉及时间部分:
public int getMinutesBetween(int time1, int time2) {
// Extract hours and minutes from compound values, which are base-100,
// effectively.
int hours1 = time1 / 100;
int hours2 = time2 / 100;
int minutes1 = time1 % 100;
int minutes2 = time2 % 100;
// Now we can perform the arithmetic based on 60-minute hours as normal.
return (hours2 - hours1) * 60 + (minutes2 - minutes1);
}
但是,我强烈建议您使用更合适的表示 - 这些不只是正常的int
值...它们实际上是 "time of day" 值,因此 LocalTime
(在 Joda Time 或 Java 8 的 java.time
中)是最合适的表示形式,IMO。