首先请原谅我的英语:-(
我对 java 的小时数有疑问。让我们看一个例子:
DateFormat datos = new SimpleDateFormat ("hh:mm:ss");
Date ac, lim;
String actual,limit;
actual="18:01:23";
limit="00:16:23";
ac=datos.parse(actual);
lim=datos.parse(limit);
if(ac.compareTo(lim)==-1){.......
我需要解决这种情况,在这种情况下,限制已过午夜,而实际时间在午夜之前。我的程序说实际已达到限制,这是不正确的,因为在示例中,它还有 6 小时要完成。
我试图用 DateFormat 类解决它,但它没有看到这种情况。我也在 Time 类中尝试过,但它的方法已被弃用。
我该如何解决这个问题?
最佳答案
在 SimpleDateFormat
中使用 HH
而不是 hh
:
DateFormat datos = new SimpleDateFormat("HH:mm:ss");
hh
是 12 小时制(小时从 1 到 12)。
HH
是 24 小时制(小时从 0 到 23)。
但除此之外,还有其他问题。 Date
类不太适合只包含时间。如果这样做,它将被解析为具有指定时间的 01-01-1970。所以 18:01:23 变成 01-01-1970、18:01:23 和 00:16:23 变成 01-01-1970、00:16:23。您可能想比较第二天的 18:01:23 和 00:16:23。
尝试这样的事情:
String actual = "18:01:23";
String limit = "00:16:23";
String[] parts = actual.split(":");
Calendar cal1 = Calendar.getInstance();
cal1.set(Calendar.HOUR_OF_DAY, Integer.parseInt(parts[0]));
cal1.set(Calendar.MINUTE, Integer.parseInt(parts[1]));
cal1.set(Calendar.SECOND, Integer.parseInt(parts[2]));
parts = limit.split(":");
Calendar cal2 = Calendar.getInstance();
cal2.set(Calendar.HOUR_OF_DAY, Integer.parseInt(parts[0]));
cal2.set(Calendar.MINUTE, Integer.parseInt(parts[1]));
cal2.set(Calendar.SECOND, Integer.parseInt(parts[2]));
// Add 1 day because you mean 00:16:23 the next day
cal2.add(Calendar.DATE, 1);
if (cal1.before(cal2)) {
System.out.println("Not yet at the limit");
}
图书馆Joda Time是一个流行的 Java 日期和时间库,比标准的 Java 日期和日历 API 设计得更好;如果您必须在 Java 中处理日期和时间,请考虑使用它。
使用 Joda Time 你可以这样做:
String actual = "18:01:23";
String limit = "00:16:23";
DateTimeFormatter df = DateTimeFormat.forPattern("HH:mm:ss");
DateTime ac = df.parseLocalTime(actual).toDateTimeToday();
DateTime lim = df.parseLocalTime(limit).toDateTimeToday().plusDays(1);
if (ac.isBefore(lim)) {
System.out.println("Not yet at the limit");
}
关于java - 比较java中的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10086053/