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

喜夏-厌秋 提交于 2019-12-10 22:59:30

问题


I will be asking a user to enter a specific time: 10AM, 12:30PM, 2:47PM, 1:09AM, 5PM, etc. I will be using a Scanner to get the user's input.

How can I parse/convert that String to a LocalTime object? Is there any built-in function in Java that will allow me to do that?


回答1:


Just use a java.time.format.DateTimeFormatter:

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

Explaining the pattern:

  • h: am/pm hour of day (from 1 to 12), with 1 or 2 digits
  • []: delimiters for optional section (everything inside it is optional)
  • :mm: a : character followed by minutes with 2 digits
  • a: designator for AM/PM

This works for all your inputs.




回答2:


If you want to parse time only, you should try parsing to LocalTime. Following is the code to implement this:

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



回答3:


Hope this will help you. I think you could do it using DateTimeFormatter and LocalDateTime parsing like below example.

    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));

Output

2017-08-13T12:10:56

Tuesday, Aug 13, 2017 12:10:56 PM

Similar posts would be Java 8 - Trying to convert String to LocalDateTime



来源:https://stackoverflow.com/questions/45595169/how-to-convert-a-given-time-string-to-a-localtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!