Java.Time.Format.Datetimeparseexception: Text Could Not Be Parsed At Index 3

java.time.format.DateTimeParseException: Text '13/11/2020' could not be parsed at index 2

Multiple issues:

  1. Your String is look like a LocalDate and LocalDateTime, it doesn't contain the time part
  2. The pattern you are using is not the same format as your String it should be dd/MM/yyyy or dd/MM/uuuu and not dd-MM-yyyy

To parse your String you need:

LocalDate date = LocalDate.parse(str, DateTimeFormatter.ofPattern("dd/MM/uuuu"));
dateTime = dateTime.plusMonths(3);

Or if you want LocalDateTime, then you can use DateTimeFormatterBuilder with 0 for hours, minutes and seconds:

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("dd/MM/uuuu")
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.toFormatter();
LocalDateTime dateTime = LocalDateTime.parse(str, formatter);
dateTime = dateTime.plusMonths(3);

and the result will be like this: 2021-02-13T00:00

Note: dateTime.plusMonths(3) is immutable so to change the value you have to assign the new value to the variable.

Caused by: java.time.format.DateTimeParseException: Text '11 2 AM' could not be parsed at index 3

try {
String time = "11 2 AM";
String parsePatter = time.contains(":") ? "hh:mm a" : "hh m a";
SimpleDateFormat parser = new SimpleDateFormat(parsePatter);
Date date = parser.parse(time);

// Result
SimpleDateFormat resultParse = new SimpleDateFormat("hh:mm a");
String result = resultParse.format(date);
System.out.println(result); // 11:02 AM
} catch (Exception ex) {
ex.printStackTrace();
}

Java LocalDateTime Text could not be parsed at index 0 exception

You need to use your format inside LocalDateTime::parse as follows:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

class Main {
public static void main(String[] args) {
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
String caseStartDate = dateFormat.format(LocalDateTime.now());
System.out.println(caseStartDate);
LocalDateTime localdatetime = LocalDateTime.parse(caseStartDate, dateFormat);
System.out.println(localdatetime);
}
}

Output:

01/05/2020 09:13
2020-05-01T09:13

Also, see how the toString() method of LocalDateTime has been overridden:

@Override
public String toString() {
return date.toString() + 'T' + time.toString();
}


Related Topics



Leave a reply



Submit