I have an strange problem when parse a string to a localdatetime
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String args[])
{
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_TIME;
LocalDateTime.parse("00:00",formatter);
}
}
Give me:
Exception in thread "main" java.time.format.DateTimeParseException: Text '00:00' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 00:00 of type java.time.format.Parsed
at java.time.format.DateTimeFormatter.createError(Unknown Source)
at java.time.format.DateTimeFormatter.parse(Unknown Source)
at java.time.LocalDateTime.parse(Unknown Source)
at Main.main(Main.java:9)
Caused by: java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 00:00 of type java.time.format.Parsed
at java.time.LocalDateTime.from(Unknown Source)
at java.time.format.Parsed.query(Unknown Source)
... 3 more
Caused by: java.time.DateTimeException: Unable to obtain LocalDate from TemporalAccessor: {},ISO resolved to 00:00 of type java.time.format.Parsed
at java.time.LocalDate.from(Unknown Source)
... 5 more
I want to parse an String with format "hour:minutes" to a localdatetime (24H format). I don't care what month/year/day is asigned, i only want the time.
I don't care what month/year/day is asigned, i only want the time.
That suggests you should be parsing it as a LocalTime
, given that that's what the string actually represents. You can then add any LocalDate
to it to get a LocalDateTime
, if you really want to pretend you've got more information then you have:
import java.time.*;
import java.time.format.*;
public class Test {
public static void main(String args[]) {
DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_TIME;
LocalTime time = LocalTime.parse("00:00",formatter);
LocalDate date = LocalDate.of(2000, 1, 1);
LocalDateTime dateTime = date.atTime(time);
System.out.println(dateTime); // 2000-01-01T00:00
}
}
If you can avoid creating a LocalDateTime
at all and just work with the LocalTime
, that would be even better.
See more on this question at Stackoverflow