Java – joda time dateformatter displays milliseconds if non-zero

With joda time, I want to display a list of dates that may or may not have milliseconds If an entry has milliseconds, it should be displayed as yyyy MM DD HH: mm: SS SSS. If it doesn't have a millis, I need it to display as yyyy MM DD HH: mm: SS

I think the general question is: is there a way to describe optional format string parameters?

I want to avoid refactoring everything I use formatter because it's a big code base

Solution

As far as I know, there is no optional mode But I think you may think too much about 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 exactly fit the substring (untested code), but you see

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>