从包含周名和时间的字符串中解析时间

我正在尝试仅解析时间,忽略字符串中的工作日,格式如下:“星期一早上 5 点”

这是我的代码:

String dateTxt = "Monday 5AM";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ha");
LocalTime lt = LocalTime.parse(dateTxt, formatter);

它抛出一个异常:
java.time.format.DateTimeParseException: Text 'Saturday 1AM' could not be parsed

如何仅从该字符串解析时间?

回答

您需要将格式更改为

"EEEE ha"

我还建议设置区域设置,以便您拥有正确的语言并支持 AM/PM

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEEE ha", Locale.ENGLISH);

我看到这个问题现在已经被编辑了,如果你只想要时间,你可以从解析LocalTime对象中提取或格式化它

LocalTime lt = LocalTime.parse(dateTxt, formatter);
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("h a", Locale.ENGLISH);
System.out.println(lt);
System.out.println(lt.format(formatter2));

05:00 凌晨
5 点


回答

如果我们想忽略这一天,那么我们可以使用以下模式:
[optional section start
]optional section end

这在解析和格式化时有不同的行为。注意:以下代码中使用了相同的模式进行解析和格式化。

    String dateTxt = "Monday 5AM";
    //for parsing day of week is ignored
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("[EEEE ]ha", Locale.ENGLISH);
    LocalTime lt = LocalTime.parse(dateTxt, formatter);
    System.out.println(lt + " - parsed local time ");
    
    //in case of formatting if data is not available 
    //then the field won't be in output
    System.out.println(lt.format(formatter) + " -local time with optnal day in format.");
    
    //the day is available so it will be there in output
    LocalDateTime ldt = LocalDateTime.now();
    System.out.println(ldt.format(formatter) + " -local date time with optnal day in format");

输出:

05:00 - parsed local time 
5AM -local time with optnal day in format.
Saturday 2PM -local date time with optnal day in format

对于格式化,如果数据不可用,则不会在输出中。

  • Now I understand what you meant with your comment to my answer, the same formatter can be reused for output as well. Nice!

以上是从包含周名和时间的字符串中解析时间的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>