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

使用 Joda-Time,我想显示一个日期列表,这些日期可能有或没有毫秒.如果某个条目有毫秒,那么它应该显示为yyyy MM dd HH:mm:ss.SSS.如果它没有millis,我需要它显示为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;
}

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

相关文章

应用场景 C端用户提交工单、工单创建完成之后、会发布一条工...
线程类,设置有一个公共资源 package cn.org.chris.concurre...
Java中的数字(带有0前缀和字符串)
在Java 9中使用JLink的目的是什么?
Java Stream API Filter(过滤器)
在Java中找到正数和负数数组元素的数量