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).