How to parse date with optional characters in format

后端 未结 3 1912
离开以前
离开以前 2020-12-12 02:20

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.

相关标签:
3条回答
  • 2020-12-12 03:03

    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 );
      }
    }
    
    0 讨论(0)
  • 2020-12-12 03:12

    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);
    
    0 讨论(0)
  • 2020-12-12 03:14

    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"));
    
    0 讨论(0)
提交回复
热议问题