SkyvrawleR
SkyvrawleR

Reputation: 412

DateTimeParseException could not be parsed at index 16 Java Seldomly Triggered

recently I faced this problem. But this happen seldomly and sometime my program run smoothly. What is triggering this exception? How to completely solve this problem:

Code:

63: DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss", Locale.US);
64: String strLocalDate = loginRecords.getLoginDate().toLocalDateTime().toString();
65: LocalDateTime lastLogin = LocalDateTime.parse(strLocalDate, formatter);

Exception text:

Exception in thread "Thread-5" java.time.format.DateTimeParseException: Text '2015-11-21T14:15' could not be parsed at index 16
    at java.time.format.DateTimeFormatter.parseResolved0(Unknown Source)
    at java.time.format.DateTimeFormatter.parse(Unknown Source)
    at java.time.LocalDateTime.parse(Unknown Source)
    at com.fesca.view.MainMenuFrame.<init>(MainMenuFrame.java:65)
    at com.fesca.control.listener.CheckingRehabDateListener.run(CheckingRehabDateListener.java:287)

Upvotes: 2

Views: 6286

Answers (3)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 78965

You do not need a DateTimeFormatter

java.time API is based on ISO 8601 and therefore you do not need a DateTimeFormatter to parse a date-time string which is already in ISO 8601 format (e.g. 2015-11-21T14:15).

What's wrong with your pattern?

Your date-time string doesn't have seconds but you have used ss. Your pattern, yyyy-MM-dd'T'HH:mm:ss can be used after removing :ss from it.

Demo:

class Main {
    public static void main(String args[]) {
        String strDateTime = "2015-11-21T14:15";
        LocalDateTime ldt = LocalDateTime.parse(strDateTime);
        System.out.println(ldt);

        // Parsing with your pattern after correction
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm");
        System.out.println(LocalDateTime.parse(strDateTime, formatter));
    }
}

Output:

2015-11-21T14:15
2015-11-21T14:15

Learn more about the modern Date-Time API from Trail: Date Time.

Upvotes: 0

Dhruv Rai Puri
Dhruv Rai Puri

Reputation: 1375

You are not getting ss in your date string sometimes as seen in error producing date - 2015-11-21T14:15. Use yyyy-MM-dd'T'HH:mm instead of yyyy-MM-dd'T'HH:mm:ss

Upvotes: 0

SatyaTNV
SatyaTNV

Reputation: 4135

Exception in thread "Thread-5" java.time.format.DateTimeParseException: Text '2015-11-21T14:15' could not be parsed at index 16

Change

yyyy-MM-dd'T'HH:mm:ss

to

yyyy-MM-dd'T'HH:mm

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm", Locale.US);

Since you are formatting upto minutes (2015-11-21T14:15) only not included seconds (ss)

or add the seconds part.

Upvotes: 2

Related Questions