简体   繁体   English

解析joda-time

[英]Parse joda-time

I have Date that look like String, and I want parse it. 我有Date看起来像String,我想解析它。
But date can look like one of many patterns. 但是日期可能看起来像许多模式中的一种。

MM/dd/yy  

or 要么

HH:mm  

or 要么

MM/dd/yy HH:mm

or 要么

MM/dd/yy HHmm   

I have code, that can parse many patterns 我有代码,可以解析许多模式

public DateTime parseDateTime(final String text)
   {
      if (StringUtils.isEmpty(text)) return null;
      int field = 0;
      DateTime dateTime = null;
      IllegalArgumentException exception = null;
      for (; field < FIELD_COUNT; ++field)
      {
         if (null != formatters[field])
         {
            try
            {
               dateTime = formatters[field].parseDateTime(text);
               break;
            }
            catch (final IllegalArgumentException e)
            {
               exception = null != exception ? exception : e;
            }
         }
      }
      if (dateTime == null)
      {
         throw exception;
      }
      return dateTime;
   }

formatters[] is array of formatters[]是一个数组

DateTimeFormatter

May you suggest a different way? 你能建议一个不同的方式吗? More simple 更简单

The first pattern contains no space, and no colon. 第一个模式不包含空格,也没有冒号。

The second one contains a colon, but no space. 第二个包含冒号,但没有空格。

The third one contains a space and a colon. 第三个包含空格和冒号。

The last one contains a space, but no colon. 最后一个包含空格,但没有冒号。

So using two indexOf() calls, you should be able to determine the pattern to apply. 因此,使用两个indexOf()调用,您应该能够确定要应用的模式。

Another way would be to use the length of the string, which is different in all the patterns (8, 5, 14 and 13). 另一种方法是使用字符串的长度,这在所有模式(8,5,14和13)中是不同的。

The SimpleDateFormat class can parse dates of any string format you specify. SimpleDateFormat类可以解析您指定的任何字符串格式的日期。 For the format rules, see the javadoc 有关格式规则,请参阅javadoc

For example, 例如,

    try
    {
        DateFormat df = new SimpleDateFormat("MM/dd/yy HHmm");
        Date date = df.parse("03/29/12 2359");
        System.out.println(date);
    }
    catch (ParseException e)
    {
        e.printStackTrace();
    }

Because parse can ignore trailing characters if all format fields have been parsed, start with the longest/most complex one and end with the shortest/simplest one. 因为解析可以忽略尾随字符,如果已经解析了所有格式字段,则从最长/最复杂的字段开始,以最短/最简单的格式结束。 Take the first one that doesn't throw an exception. 拿第一个没有抛出异常的东西。

In your case: 在你的情况下:

{
new SimpleDateFormat("MM/dd/yy HH:mm"),
new SimpleDateFormat("MM/dd/yy HHmm"),
new SimpleDateFormat("MM/dd/yy"),
new SimpleDateFormat("HH:mm")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM