How to make a split second and timezone in the template optional?

"yyyy-MM-dd'T'HH:mm:ss.SSS Z" 

I use in

 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSz"); 

I'm trying to do all this for the class.

 public class DateAdapter extends XmlAdapter<String, Date> { private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS Z"); @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); } } } 
  • one
    In which regular, where is it used? if you don’t need them just don’t point them out - Keeplod
  • Perhaps you need to use (...)? where ... is the optional regular expression section - cpp questions
  • @Keeplod updated the question - Roberto
  • You wrote to SimpleDateFormat ? And what will happen if the timeline comes without fractions of seconds? An exception? - gil9red 1:01 pm
  • @ gil9red, yes, I wrote inside SimpleDateFormat. If without fractions of seconds comes now, then yes an exception. I just need to share - seconds were optional. - Roberto

2 answers 2

Check the incoming date for fractions of seconds (as I understand it - this is a point + 3 digits)

 if (date.matches(".*(\\.(\d){3}){1}z") { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSz"); } else { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); } 
  • Does any text that does not match the regular expression exactly fall into the else? - cpp questions
  • @cppquestions It depends on the application and the input data. I would do the checks, but I think my example is enough for the author of the question to understand the meaning of the implementation. - Vladimir Yarovoy

I did this method that converted the string to a date.

 public static Date getDateFromString(String value, boolean silent) { Map<String, String> formatsMap = ImmutableMap.of( "\\d{1,2}\\.\\d{2}\\.\\d{4}", "dd.MM.yyyy", "\\d{1,2}\\.\\d{2}\\.\\d{4}\\s+\\d{2}:\\d{2}:\\d{2}", "dd.MM.yyyy HH:mm:ss", "\\d{4}-\\d{2}-\\d{2}", "yyyy-MM-dd", "\\d{4}-\\d{2}-\\d{2}\\s+\\d{2}:\\d{2}:\\d{2}", "yyyy-MM-dd HH:mm:ss"); try { if (StringUtils.isNotBlank(value)) { String trimmedValue = value.trim(); for (Map.Entry<String, String> entry : formatsMap.entrySet()) { Pattern pattern = Pattern.compile(entry.getKey()); Matcher matcher = pattern.matcher(trimmedValue); if (matcher.matches()) { return new SimpleDateFormat(entry.getValue()).parse(value); } } } if (silent) { return null; } throw new IllegalArgumentException("Неподдерживаемый формат даты!"); } catch (Exception e) { if (silent) { return null; } throw new IllegalArgumentException("Неподдерживаемый формат даты!"); } } 

You can add other date templates in formatsMap , or specify only those that you need.