如何使用可选字符解析日期格式 [英] How to parse date with optional characters in format
问题描述
我有以下两个日期:
- 2009年10月8日
- 2010年5月13日
我正在使用Jackson将日期从rest api转换为joda Datetime.
I am using Jackson to convert the date from an rest api to joda Datetime.
我认为模式"dd MMM. yyyy"
可以工作,但是"may"没有点,因此在该点崩溃.
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?
jackson中的注释为:
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.
推荐答案
鉴于OP的新注释和要求,解决方案是使用自定义反序列化器:
Given OP's new comment and requirements, the solution is to use a custom deserializer:
您将执行以下操作:
@JsonDeserialize(using = MyDateDeserializer.class)
class MyClassThatHasDateField {...}
在此处查看教程: http://www.baeldung.com/jackson-deserialization
在此处查看示例:使用Jackson进行自定义JSON反序列化
旧答案:
您可以使用Java的SimpleDateFormat
之一:
You can use Java's SimpleDateFormat
and either:
- 使用正则表达式选择合适的模式
- 只需尝试一下并捕获(并忽略)异常
示例:
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 );
}
}
这篇关于如何使用可选字符解析日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!