Java 如果非零,Joda-Time DateFormatter 显示毫秒
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2806848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Joda-Time DateFormatter to display milliseconds if nonzero
提问by Mike
Using Joda-Time, I want to display a list of dates that may or may not have milliseconds on them. If a certain entry has milliseconds, then it should be displayed like yyyy MM dd HH:mm:ss.SSS
. If it doesn't have the millis, I need it displayed as yyyy MM dd HH:mm:ss
.
使用Joda-Time,我想显示一个日期列表,这些日期可能有也可能没有毫秒。如果某个条目有毫秒,那么它应该显示为yyyy MM dd HH:mm:ss.SSS
。如果它没有毫秒,我需要将其显示为yyyy MM dd HH:mm:ss
.
I suppose the general question is: Is there a way to describe an optional format string parameter?
我想一般的问题是:有没有办法描述一个可选的格式字符串参数?
(I'd like to avoid refactoring all of the places that I use formatters since this is a large code base.)
(我想避免重构我使用格式化程序的所有地方,因为这是一个大型代码库。)
采纳答案by MetroidFan2002
As far as I know, there's no optional patterns. However, I think you may be overthinking 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 be exactly right for the substring (untested code), but you get the idea.
长度可能不完全适合子字符串(未经测试的代码),但您明白了。