如何从字符串中解析时间(小时、分钟)?

kip*_*ip2 3 java jodatime datetime-format android-jodatime

有谁知道如何从看起来像 "01:20" -> 1:20AM 和 "21:20" -> 9:20PM 的字符串中解析时间(小时、分钟和 AM/PM)?大多数解决方案似乎都假设或需要 Date 或 Calendar 对象。

我的输入时间实际上来自 TimePickerDialog(特别是这个 MaterialDateTimePicker 实现,所以我只收到小时、分钟和秒(整数)。

我希望能够以友好的方式格式化用户选择的时间,即 12:30PM、02:15AM 等。

我正在尝试使用 Joda 时间:

fun formattedTime(timeStr: String): String {
    // Get time from date
    val timeFormatter = DateTimeFormat.forPattern("h:mm a")
    val displayTime = timeFormatter.parseLocalTime(timeStr)
    return displayTime.toString()
}
Run Code Online (Sandbox Code Playgroud)

但是我在输入字符串(例如“1:20”)时收到此错误: java.lang.IllegalArgumentException: Invalid format: "1:20" is too short

我也研究过SimpleDateFormat但它似乎需要一个完整的日期时间字符串,例如在这个相关问题中

Jan*_*Jan 5

正如@ole-vv 所指出的,SimpleDateFormat已经看到了更好的日子 - 所以今天你可以使用 java.time 包来完成这项工作:

java.time.format.DateTimeFormatter target2 = 
     java.time.format.DateTimeFormatter.ofPattern("h:mm a");
java.time.format.DateTimeFormatter source2 = 
     java.time.format.DateTimeFormatter.ofPattern("HH:mm");

System.out.println("01:30 -> " + target2.format(source2.parse("01:30")));
System.out.println("21:20 -> " + target2.format(source2.parse("21:20")));
Run Code Online (Sandbox Code Playgroud)

产生结果

01:30 -> 1:30 AM
21:20 -> 9:20 PM
Run Code Online (Sandbox Code Playgroud)

正如预期的那样。

在 Joda-Time 中,您可以按照@meno-hochschild 在下面的回答中指出的那样对其进行编码。

使用SimpleDateFormat它看起来像这样:

    SimpleDateFormat target = new SimpleDateFormat("h:mm a");
    SimpleDateFormat source = new SimpleDateFormat("HH:mm");
    System.out.println("01:30 -> " + target.format(source.parse("01:30")));
    System.out.println("21:20 -> " + target.format(source.parse("21:20")));
Run Code Online (Sandbox Code Playgroud)

这将从 24 小时时间解析到 12 小时显示

    01:30 -> 1:30 AM
    21:20 -> 9:20 PM      
Run Code Online (Sandbox Code Playgroud)

这一切都取决于小时的格式 - 解析你需要 24 小时(格式 HH),输出你需要 12 小时加上上午 / 下午 - 格式是 h。

如果您希望 01:30 成为 PM,则必须将其添加到要以某种方式解析的字符串中:

   System.out.println("01:30 pm-> " + target.format(target.parse("01:30 pm")));
Run Code Online (Sandbox Code Playgroud)

导致

   01:30 pm-> 1:30 PM
Run Code Online (Sandbox Code Playgroud)

  • 请不要教年轻人使用早已过时且臭名昭著的“SimpleDateFormat”类。Joda-Time(在问题中使用)更好。而今天,我们在 [`java.time`,现代 Java 日期和时间 API](https://docs.oracle.com/javase/tutorial/datetime/) 及其 `DateTimeFormatter` 方面还有更好的表现。是的,您可以在 Android 上使用它。对于较旧的 Android,请参阅 [如何在 Android 项目中使用 ThreeTenABP](/sf/ask/2724592811/)。 (2认同)