How to convert the input date 2019-03-04T18: 55: 05.591 + 03: 00 to the timestamp to save to the oracle database?

I use simpleDateFormat to parse the date 2019-03-04T18: 55: 05.591 + 03: 00 and get the Date.

public class DateAdapter extends XmlAdapter<String, Date> { private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); @Override public String marshal(Date v) throws Exception { synchronized (dateFormat) { return dateFormat.format(v); } } @Override public Date unmarshal(String v) throws Exception { synchronized (dateFormat) { return dateFormat.parse(v); } } } 

But, there is a case when they send a date without specifying milliseconds and I get a parsing error. 2019-03-04T18: 55: 05 + 03: 00

How can this be avoided?

    2 answers 2

     public class DateAdapter extends XmlAdapter<String, Date> { private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); @Override public String marshal(Date v) throws Exception { synchronized (dateFormat) { return dateFormat.format(v); } } @Override public Date unmarshal(String v) { return Date.from(java.time.ZonedDateTime.parse(v).toInstant()); } } 

    I would suggest such a solution. In my opinion, this is easier than specifying 2 formats ...

      As an additional solution, it is to write a utilitarian method that will select the desired template:

        private static final List<SimpleDateFormat> dateFormats = Arrays.asList( new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"), new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX") ); public static Date parseToDate(String input) { if (input != null) { for (SimpleDateFormat dateFormat : dateFormats) { try { return dateFormat.parse(input); } catch (ParseException e) { } } } return null; } public static Timestamp parseToTimestamp(String input) { if (input != null) { for (SimpleDateFormat dateFormat : dateFormats) { try { Date date = dateFormat.parse(input); return new Timestamp(date.getTime()); } catch (ParseException e) { } } } return null; }