0

I need to convert my String to time without the date. I used SimpleDateFormat and it worked. But what I need is from Localdatetime in java.

String str = "10:30:20 PM";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm:ss a");
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);

But it is giving me this error:

Exception in thread "main" java.time.format.DateTimeParseException: Text '10:30:20 PM' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 22:30:20 of type java.time.format.Parsed

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Codeninja
  • 322
  • 1
  • 4
  • 18
  • What about [`LocalTime#parse`](https://docs.oracle.com/javase/8/docs/api/java/time/LocalTime.html#parse-java.lang.CharSequence-java.time.format.DateTimeFormatter-)? – dan1st Apr 09 '20 at 06:33
  • 2
    LocalTime time = LocalTime.parse("10:30:20 PM", DateTimeFormatter.ofPattern("hh:mm:ss a")) – ernest_k Apr 09 '20 at 06:33
  • almost same to this https://stackoverflow.com/questions/61114302/zoneddatetime-parse-not-working-for-parsing-time-with-am-or-pm/61114425#61114425` – Ryuzaki L Apr 09 '20 at 06:37
  • @ernest_k your answer is working – Codeninja Apr 09 '20 at 06:38

2 Answers2

3

You could use Locale with your DateTimeFormatter -

String str = "10:30:20 PM";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("hh:mm:ss a",Locale.ENGLISH);
LocalTime time = LocalTime.parse(str, formatter);
System.out.println(time);

And also note you have to use LocalTime.parse() here, since your string in the date doesn't contain date part.

Razib
  • 10,965
  • 11
  • 53
  • 80
2

What you need is LocalTime & not LocalDateTime. You can try this as well:

LocalTime localTime = LocalTime.parse("10:45:30 PM", DateTimeFormatter.ofPattern("hh:mm:ss a"));
System.out.println(localTime);

If you have time in 24 hr format:

LocalTime localTime = LocalTime.parse("22:45:30", DateTimeFormatter.ofPattern("HH:mm:ss"));
System.out.println(localTime);
Saurabhcdt
  • 1,010
  • 1
  • 12
  • 24