'trying to parse String into Date and time as Date(data type) in java [closed]
String input = "2022-04-05 21:11:06";
required output:
Date output = 2022-04-05 21:11:06;
My code
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
Date var4 = df.parse(input);
but I got error
Exception in thread "main" java.text.ParseException: Unparseable date: "2022-04-05 21:11:06"
Solution 1:[1]
You shouldn't use the old Date and SimpleDateFormat classes. Instead, use LocalDateTime, ZonedDateTime, and DateTimeFormatter
LocalDateTime dt = LocalDateTime.parse(
"2022-04-05 21:11:06",
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
);
Solution 2:[2]
You are specifying wrong SimpleDateFormat. change this
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
to SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Solution 3:[3]
As Alexey R mentioned your pattern need some correction:
String input = "2022-04-05 21:11:06";
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date v = df.parse(input);
System.out.println(v);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Zabuzard |
| Solution 2 | Denis Michael Kamukama |
| Solution 3 | Ashish Patil |
