加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 05:42:49 所属栏目:Java 来源:网络整理
导读:使用 Joda-Time,我想显示一个日期列表,这些日期可能有或没有毫秒.如果某个条目有毫秒,那么它应该显示为yyyy MM dd HH:mm:ss.SSS.如果它没有millis,我需要它显示为yyyy MM dd HH:mm:ss. 我想一般的问题是:有没有办法描述可选的格式字符串参数? (我想避
使用 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;
}

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读