I recommend you switch from the outdated and error-prone java.util
date-time API to the rich set of modern date-time API.
Define a formatter object:
DateTimeFormatter.ofPattern("u-M-d H:m:s.SSSXXX")
…and use it for parsing both kinds of date-time strings.
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(final String[] args) {
// Define the formatter
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("u-M-d H:m:s.SSSXXX");
// Test date-time strings
String[] strDateArr = { "2020-07-01 13:06:10.178+05:30", "2020-07-01 13:06:10.18+05:30" };
OffsetDateTime odt;
for (String strDate : strDateArr) {
// Parse a date-time string from the array of test date-time strings
odt = OffsetDateTime.parse(strDate, formatter);
System.out.println(odt);
}
}
}
Output:
2020-07-01T13:06:10.178+05:30
2020-07-01T13:06:10.180+05:30
Note that you can use OffsetDateTime
directly with the PreparedStatement
and the ResultSet
objects without converting it to any other date-time object e.g.
Setting the OffsetDateTime object as a parameter to the PreparedStatement object:
pst.setObject(index, odt);
Getting the OffsetDateTime object from the Resultset object:
OffsetDateTime odt = rs.getObject(index, OffsetDateTime.class);
Update
Using legacy API:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(final String[] args) throws ParseException {
// Test date-time strings
String[] strDateArr = { "2020-07-01 13:06:10.178+05:30", "2020-07-01 13:06:10.18+05:30" };
// Define the format
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSXXX");
Date date;
for (String strDate : strDateArr) {
// Parse a date-time string from the array of test date-time strings
date = sdf.parse(strDate);
System.out.println(date);
}
}
}
Output:
Wed Jul 01 08:36:10 BST 2020
Wed Jul 01 08:36:10 BST 2020
Backport of the Java SE 8 date-time classes to Java SE 6 and 7:
Check ThreeTen-Backport and How to use ThreeTenABP