TL;DR
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("hh:mm a", Locale.ENGLISH);
String input = "03:00 PM";
LocalTime time = LocalTime.parse(input, inputFormatter);
System.out.println(time);
打印出来
15:00
编辑:由于您的时间格式是英文,因此使用此格式化程序可能会更简洁:
DateTimeFormatter inputFormatter
= DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT)
.withLocale(Locale.ENGLISH);
它几乎匹配。后一种格式化程序将 10 小时前的几小时格式化为只有一位数字,例如 5:12 AM,但在解析时也接受两位数字,因此它可以工作。
java.time
我建议您使用java.time 中的LocalTime 来表示一天中的时间,这正是它的用途。因此,它为您提供了良好的建模和自记录代码。
其他答案是正确的,但很差。虽然您应该为您的任务使用库类,但至少出于三个原因,您不应该使用SimpleDateFormat 和Date。 (1) 陈旧过时,设计不良; (2) DateFormat 和 SimpleDateFormat 特别是出了名的麻烦; (3) Date 不代表一天中的时间。
比较时间
LocalTime anotherTime = LocalTime.parse("09:00 AM", inputFormatter);
if (anotherTime.isBefore(time)) {
System.out.println("" + anotherTime + " comes before " + time);
} else {
System.out.println("" + time + " comes before " + anotherTime);
}
打印出来
09:00 comes before 15:00
再次,使用LocalTime 进行比较,它比使用格式化字符串更清晰。可能更好,LocalTime 实现了Comparable,因此您可以使用Collections.sort() 和其他依赖于对象自然排序的函数。
如果你确实想要一个格式化的字符串,第一个选项是LocalTime.toString():
String formattedTime = time.toString();
System.out.println(formattedTime);
这将打印与我们上面得到的相同的输出,15:00。如果您想要不同的格式,请定义第二个DateTimeFormatter 并在LocalTime.format() 中使用它。
问题:我可以在 Android 上使用 java.time 吗?
是的,您可以在 Android 上使用 java.time。它只需要至少 Java 6。
- 在 Java 8 及更高版本以及较新的 Android 设备上,内置了现代 API。
- 在 Java 6 和 7 中,获取 ThreeTen Backport,即新类的后向端口(对于 JSR 310,ThreeTen;请参阅底部的链接)。
- 在较旧的 Android 上使用 ThreeTen Backport 的 Android 版本。它被称为 ThreeTenABP。并确保从
org.threeten.bp 导入日期和时间类以及子包。
链接