Mike
Mike

Reputation: 536

Joda-Time DateFormatter to display milliseconds if nonzero

Using Joda-Time, 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.)

Upvotes: 8

Views: 37188

Answers (1)

MetroidFan2002
MetroidFan2002

Reputation: 29908

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

Upvotes: 21

Related Questions