vihang shah
vihang shah

Reputation: 608

Exception in thread "main" java.time.format.DateTimeParseException: Text '14/Oct/2016 23:09:25.2110 +0530' could not be parsed at index 0

I was just playing with Java 8 Date time API.

My code looks like this.

LocalDateTime date=LocalDateTime.now(ZoneId.of("America/New_York"));
System.out.println("date now:"+date);
String ormat = ZonedDateTime.now().format(DateTimeFormatter.ofPattern("dd/MMM/yyyy HH:mm:ss"));
//=date.format(DateTimeFormatter.ofPattern("dd/MMM/yyyy'T'hh:mm:ss.SX Z"));
LocalDateTime date2=LocalDateTime.parse(format);

System.out.println("dsate now:"+date2);

But it is showing this error

Exception in thread "main" java.time.format.DateTimeParseException: Text '14/Oct/2016 23:13:57' could not be parsed at index 0

I tried with this pattern

String format=ZonedDateTime.now().format(DateTimeFormatter.ofPattern("dd/MMM/yyyy HH:mm:ss.SSSS Z"));

Still didn't work.

I checked the answers here and here.

Edit: One thing also I want to know what if I want my date object only in this format?

Edit 2: What I try to achieve is that have some date and time what I got using localDateTime and I want to format it using the formatter I have used in code.

Upvotes: 1

Views: 4216

Answers (1)

Unknown
Unknown

Reputation: 2137

Your format2 produces the String 14/Oct/2016 23:26:38

You try to parse that input String with the ISO_LOCAL_DATE_TIME (yyyy-MM-dd'T'hh:mm:ss). That is why you were getting the error.

You have to pass the date formatter to the parse method

LocalDateTime date2=LocalDateTime.now(ZoneId.of("America/New_York"));
System.out.println("date now:"+date2);
String format2=ZonedDateTime.now().format(DateTimeFormatter.ofPattern("dd/MMM/yyyy HH:mm:ss"));
System.out.println(format2);
//=date.format(DateTimeFormatter.ofPattern("dd/MMM/yyyy'T'hh:mm:ss.SX Z"));
LocalDateTime date3=LocalDateTime.parse(format2,
                DateTimeFormatter.ofPattern("dd/MMM/yyyy HH:mm:ss").withLocale(Locale.ENGLISH));

System.out.println("dsate now:"+date3);

Output:

dsate now:2016-10-14T23:26:38

Edit after the comment:

You can directly format the LocalDateTime

LocalDateTime date2=LocalDateTime.now(ZoneId.of("America/New_York"));
System.out.println("date now:"+date2);
String myDate1 = date2.format(DateTimeFormatter.ofPattern("dd/MMM/yyyy HH:mm:ss").withLocale(Locale.ENGLISH));
System.out.println("dsate now:"+myDate1);

Upvotes: 1

Related Questions