简体   繁体   中英

Parse joda-time

I have Date that look like String, and I want parse it.
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

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.

Another way would be to use the length of the string, which is different in all the patterns (8, 5, 14 and 13).

The SimpleDateFormat class can parse dates of any string format you specify. For the format rules, see the 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")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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