Home » Java » Error converting String to java.sql.LocalDateTime-Exceptionshub

Error converting String to java.sql.LocalDateTime-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I tried converting string to LocalDateTime. Here is my code

String val = "2015-07-18T13:32:56.971-0400"
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZ");
java.time.LocalDateTime dateTime = java.time.LocalDateTime.parse(val, formatter);

But doing so I am getting the following errors

The method ofPattern(String) is undefined for the type DateTimeFormatter
The method parse(CharSequence, DateTimeFormatter) in the type LocalDateTime is not applicable for the arguments (String, DateTimeFormatter)

Can someone suggest me what to do

How to&Answers:

Your code is mostly right. First, be sure you’re importing the correct packages:

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

Second, your first line has a typo (-) in the first character of the String val and is missing a semicolon:

// Remove - from the String and put ; at the end
// String val = "-2015-07-18T13:32:56.971-0400"
String val = "2015-07-18T13:32:56.971-0400";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZ");
LocalDateTime dateTime = java.time.LocalDateTime.parse(val, formatter);
//Print to test:
System.out.println(dateTime);
//Result on the console: 2015-07-18T13:32:56.971

Answer:

Remove the leading - from your String.

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

String val = "2015-07-18T13:32:56.971-0400";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZZ");
LocalDateTime dateTime = LocalDateTime.parse(val, formatter);
System.out.println(dateTime);    

2015-07-18T13:32:56.971