views:

23

answers:

1

I want to display a list of dates that may or may not have milliseconds on them. If a certain entry has milliseconds, then it should be displayed like yyyy MM dd HH:mm:ss.SSS. If it doesn't have the millis, I need it displayed as yyyy MM dd HH:mm:ss.

I suppose the general question is: Is there a way to describe an optional format string parameter?

(I'd like to avoid refactoring all of the places that I use formatters since this is a large code base.)

A: 

As far as I know, there's no optional patterns. However, I think you may be overthinking your problem.

// Sample variable name - you'd probably name this better.
public static DateTimeFormat LONG_FORMATTER = DateTimeFormatter.forPattern("yyyy MM dd HH:mm:ss.SSS");

// Note that this could easily take a DateTime directly if that's what you've got.
// Hint hint non-null valid date hint hint.
public static String formatAndChopEmptyMilliseconds(final Date nonNullValidDate) {
    final String formattedString = LONG_FORMATTER.print(new DateTime(nonNullValidDate.getTime());
    return formattedString.endsWith(".000") ? formattedString.substring(0, formattedString.length() - 4) : formattedString;
}

The length may not be exactly right for the substring (untested code), but you get the idea.

MetroidFan2002
Thanks. I extended `DateTimeFormatter` to nest this logic right there, and it works pretty well. I can still pass around my formatter and get the results I want. (And I guess I was overthinking it. Heh.)
Mike