I have the following two dates:
I am using Jackson to convert the date from an rest api to joda Datetime.
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:
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 );
}
}
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);
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"));