I want to parse a date string like 2011-11-30
like this:
LocalDateTime.parse("2011-11-30", DateTimeFormatter.ISO_LOCAL_DATE)
But I get the following exception:
java.time.format.DateTimeParseException: Text '2011-11-30' could not be parsed:
Unable to obtain LocalDateTime from TemporalAccessor
If I pass a date and time string everything works as expected:
LocalDateTime.parse("2011-11-30T23:59:59", DateTimeFormatter.ISO_LOCAL_DATE_TIME)
How can I parse a date like 2011-11-30
to a LocalDateTime (with a default time)?
Parsing date and time To create a LocalDateTime object from a string you can use the static LocalDateTime. parse() method. It takes a string and a DateTimeFormatter as parameter. The DateTimeFormatter is used to specify the date/time pattern.
The most common ISO Date Time Format yyyy-MM-dd'T'HH:mm:ss. SSSXXX — for example, "2000-10-31T01:30:00.000-05:00".
String str = "2016-03-04 11:30"; DateTimeFormatter formatter = DateTimeFormatter. ofPattern("yyyy-MM-dd HH:mm"); LocalDateTime dateTime = LocalDateTime. parse(str, formatter); Done, that's all is required to convert a formatted String to transform into a LocalDateTime.
E.g: 2011-08-12T20:17:46.384Z. The T doesn't really stand for anything. It is just the separator that the ISO 8601 combined date-time format requires. You can read it as an abbreviation for Time. The Z stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).
As @JB Nizet suggested, the following works
LocalDate localDate = LocalDate.parse("2011-11-30", DateTimeFormatter.ISO_LOCAL_DATE);
LocalDateTime localDateTime = localDate.atTime(23, 59, 59);
System.out.println(localDateTime); // 2011-11-30T23:59:59
How can I parse a date like 2011-11-30 to a LocalDateTime (with a default time)?
LocalDate
LocalDateTime
atTime()
method to set your default timeNote: Use of DateTimeFormatter.ISO_LOCAL_DATE
is superfluous for parse()
, see API LocalDate#parse()
The sample below use some magic numbers, wich should be avoid (What is a magic number, and why is it bad?).
Instead of using the method atTime(hour, minute, second),
LocalDate localDate = LocalDate.parse("2011-11-30", DateTimeFormatter.ISO_LOCAL_DATE);
LocalDateTime localDateTime = localDate.atTime(23, 59, 59);
you can use the LocalTime constants, such as LocalTime.MAX, (23:59:59), LocalTime.MIN (00:00:00), LocalTime.MIDNIGHT (23:59:59) or LocalTime.NOON (12:00:00)
LocalDate localDate = LocalDate.parse("2011-11-30", DateTimeFormatter.ISO_LOCAL_DATE);
LocalDateTime localDateTime = LocalDateTime.of(localDate, LocalTime.MIN);
It is better for maintainability and cross-reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With