我想创建一个程序,检查输入是否大于 8h30m 。我该如何做到这一点?我想可能是关于java.util.Calendar
或Date
,但我不知道这些事情是如何运作的。
答案 0 :(得分:1)
答案 1 :(得分:1)
使用Java 8中的Duration:
String input = "8h";
Duration duration = Duration.parse("PT" + input);
Duration compared = Duration.ofHours(8).plus(Duration.ofMinutes(30));
int compare = duration.compareTo(compared); // -1
// compare would be 0 for input="8h30m" and 1 for input="8h40m"
修改 - 您也可以减去时间,例如获取秒数:
Duration diff = duration.minus(compared);
int seconds = diff.getSeconds();
答案 2 :(得分:0)
如果你想要的是检查当前时间是否在另一个时间之前,你可以这样做:
public Boolean foo() {
Calendar currentlyCal = Calendar.getInstance(); // This is the currently time.
Calendar calToCheck = Calendar.getInstance();
calToCheck.set(Calendar.HOUR_OF_DAY, 8);
calToCheck.set(Calendar.MINUTE, 30);
return currentlyCal.before(calToCheck); // or use after() instead of before() if it's what you want.
}
修改
区别:
public void getDifference(Calendar cal1, Calendar cal2) {
long diff = cal2.getTimeInMillis() - cal.getTimeInMillis();
long seconds = diff/1000;
long hour = seconds/3600;
seconds = seconds%3600;
long minutes = seconds/60;
seconds = seconds%60;
// .. do something
}