Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
196 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 );
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...