本文介绍了如何使用格式中的可选字符解析日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下两个日期:

  • 2009 年 10 月 8 日
  • 2010 年 5 月 13 日

我正在使用 Jackson 将日期从 rest api 转换为 joda 日期时间.

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:

  1. 使用正则表达式选择合适的模式
  2. 只需尝试它们并捕获(并忽略)异常

示例:

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

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

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

这篇关于如何使用格式中的可选字符解析日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-18 02:42