2

I have the following two dates:

  • 8 Oct. 2009
  • 13 May 2010

I am using Jackson to convert the date from an rest api to joda Datetime.

I thought the pattern "dd MMM. yyyy" would work but the "may" has no dot so it crashes at that point.

Is there a solution or do I have to write my own datetime parser?

The annotation in jackson is:

@JsonFormat(pattern = "dd MMM. yyyy", timezone = "UTC", locale = "US", )
@JsonProperty(value = "date")
private DateTime date;

So there is only one date pattern allowed.

Fabi
  • 23
  • 1
  • 4

3 Answers3

3

Given OP's new comment and requirements, the solution is to use a custom deserializer:

You would do something like this:

@JsonDeserialize(using = MyDateDeserializer.class)
class MyClassThatHasDateField {...}

See tutorial here: http://www.baeldung.com/jackson-deserialization

See an example here: Custom JSON Deserialization with Jackson

OLD ANSWER:

You can use Java's SimpleDateFormat and either:

  1. Use a regex to choose the proper pattern
  2. Simply try them and catch (and ignore) the exception

Example:

String[] formats = { "dd MMM. yyyy", "dd MM yyyy" };

for (String format : formats)
{
    try
    {
        return new SimpleDateFormat( format ).parse( theDateString );
    }
    catch (ParseException e) {}
}

OR

String[] formats = { "dd MMM. yyyy", "dd MM yyyy" };
String[] patterns = { "\\d+ [a-zA-Z]+\. \d{4}", "\\d+ [a-zA-Z]+ \d{4}" };

for ( int i = 0; i < patterns.length; i++ )
{
  // Create a Pattern object
  Pattern r = Pattern.compile(patterns[ i ] );

  // Now create matcher object.
  Matcher m = r.matcher( theDateString );

  if (m.find( )) {
     return new SimpleDateFormat( formats[ i ] ).parse( theDateString );
  }
}
Community
  • 1
  • 1
Don Rhummy
  • 24,730
  • 42
  • 175
  • 330
  • The problem is that i this date comes from an rest service and i parse it automatically and in the jackson annotation jsonformat allows only one pattern. in normal source code the above problem would be easy to solve – Fabi Jun 30 '16 at 13:49
0

You could just define two formatters and use the one with a dot, if it is present in the string.

String dateString = "8 Oct. 2009";

DateTimeFormatter formatWithDot    = DateTimeFormat.forPattern("dd MMM. yyyy");
DateTimeFormatter formatWithoutDot = DateTimeFormat.forPattern("dd MMM yyyy");

DateTime date = dateString.indexOf('.') > -1
    ? formatWithDot.parseDateTime(dateString)
    : formatWithoutDot.parseDateTime(dateString);
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
0

There would also be a different way by fixing the string for parsing:

String date = "13 May. 2009";
DateTime result = DateTime.parse(date.replace(".",""),
DateTimeFormat.forPattern("dd MMM yyyy"));
wake-0
  • 3,918
  • 5
  • 28
  • 45