使用Joda-Time,我想显示可能有或没有毫秒的日期列表。如果某个条目有毫秒,那么它应该显示为yyyy MM dd HH:mm:ss.SSS
. 如果它没有毫秒,我需要它显示为yyyy MM dd HH:mm:ss
.
我想一般的问题是:有没有办法描述一个可选的格式字符串参数?
(我想避免重构我使用格式化程序的所有地方,因为这是一个大型代码库。)
据我所知,没有可选模式。但是,我认为您可能过度考虑了您的问题。
// 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;
}
对于子字符串(未经测试的代码),长度可能并不完全正确,但您明白了。