HH
の代わりに使用hh
してくださいSimpleDateFormat
:
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");
}
ライブラリJodaTimeは、標準のJava日付およびカレンダーAPIよりもはるかに優れた設計の人気のあるJava日付および時刻ライブラリです。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");
}