Joda-Time DateFormatter如果非零则显示毫秒

时间:2010-05-10 22:19:34

标签: java datetime jodatime

使用Joda-Time,我想显示一个日期列表,这些日期可能有毫秒,也可能没有毫秒。如果某个条目有毫秒,那么它应该显示为yyyy MM dd HH:mm:ss.SSS。如果它没有millis,我需要它显示为yyyy MM dd HH:mm:ss

我想一般的问题是:有没有办法描述可选的格式字符串参数?

(我想避免重构我使用格式化程序的所有地方,因为这是一个很大的代码库。)

1 个答案:

答案 0 :(得分:14)

据我所知,没有可选的模式。但是,我认为你可能会过度思考你的问题。

// 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;
}

长度可能不完全适合子字符串(未经测试的代码),但你明白了。