Home > front end >  java.time.format.DateTimeParseException: Text '103545' could not be parsed at index 2
java.time.format.DateTimeParseException: Text '103545' could not be parsed at index 2

Time:11-11

I'm trying to parse two different dates and calculate the difference between them, but the next error appears:

java.time.format.DateTimeParseException: Text '103545' could not be parsed at index 2

Here's the code:

    String thisDate= mySession.getVariableField(myVariable).toString().trim();
    
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMyyyy");
    LocalDate theDate= LocalDate.parse(thisDate, formatter);

CodePudding user response:

The problem here is the date parser has to recieve a date in the format specified (in this case "ddMMyyyy")

For example, this is what you would need to input for the parser to return a valid date:

String thisDate = '25Sep2000';

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMyyyy");
LocalDate theDate = LocalDate.parse(thisDate, formatter);

I think what you want is to convert a date in milliseconds to a date with a specific format. This is what you can do:


//Has to be made long because has to fit higher numbers
long thisDate = 103545;    //Has to be a valid date in milliseconds
  
DateFormat formatter = new SimpleDateFormat("ddMMyyyy");    //You can find more formatting documentation online
Date theDate = new Date(thisDate);

String finalDate = formatter.format(theDate);

CodePudding user response:

That’s as expected (approximately).

Your format pattern string, ddMMyyyy specifies two digits day of month, two digits month and (at least) four digits year for a total of (at least) eight (8) digits. So when you give it a string consisting of only 6 digits, parsing will necessarily fail.

If your user or another system is required to give you a date in ddMMyyyy format and they give you 103545, they are making an error. Your validation caught the error, which is a good thing. You will probably want to give them a chance to try again and give you a string like for example 10112021 (for 10 November 2021).

In case (just guessing) 103545 was meant to denote a time of day, 10:35:45 then you need to use the LocalTime class for it, and you also need to change the format pattern string to specify hours, minutes and seconds instead of year, month and date.

    String thisDate = "103545";

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HHmmss");
    LocalTime theTime = LocalTime.parse(thisDate, formatter);
    System.out.println(theTime);

Output from this snippet is:

10:35:45

  • Related