如何将给定时间(字符串)转换为 LocalTime?

How to convert a given time (String) to a LocalTime?

我会要求用户输入具体时间:上午 10 点、12:30PM、2:47PM、1:09AM、下午 5 点等。 我将使用 Scanner 来获取用户的输入。

我如何 parse/convert 那个 StringLocalTime 对象? Java 中是否有任何内置函数可以让我这样做?

希望对您有所帮助。我认为你可以使用 DateTimeFormatterLocalDateTime 解析来做到这一点,如下例所示。

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEEE, MMM d, yyyy HH:mm:ss a");

    String date = "Tuesday, Aug 13, 2017 12:10:56 PM";
    LocalDateTime localDateTime = LocalDateTime.parse(date,  formatter);
    System.out.println(localDateTime);
    System.out.println(formatter.format(localDateTime));

输出

2017-08-13T12:10:56

2017 年 8 月 13 日星期二12:10:56下午

类似的帖子是

如果你只想解析时间,你应该尝试解析到LocalTime。以下是实现它的代码:

DateTimeFormatter parseFormat = new DateTimeFormatterBuilder().appendPattern("hh[:mm]a").toFormatter();
LocalTime localTime = LocalTime.parse(timeValue, parseFormat);

只需使用 java.time.format.DateTimeFormatter:

DateTimeFormatter parser = DateTimeFormatter.ofPattern("h[:mm]a");
LocalTime localTime = LocalTime.parse("10AM", parser);

解释模式:

  • h: am/pm 一天中的小时(从 1 到 12),有 1 位或 2 位数字
  • []:可选部分的分隔符(其中的所有内容都是可选的)
  • :mm:一个 : 字符后跟带 2 位数字的分钟
  • a:AM/PM
  • 的代号

这适用于您的所有输入。