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
.
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.)
The most common ISO Date Format yyyy-MM-dd — for example, "2000-10-31". DATE_TIME. The most common ISO Date Time Format yyyy-MM-dd'T'HH:mm:ss. SSSXXX — for example, "2000-10-31T01:30:00.000-05:00".
Joda-Time provides a comprehensive formatting system. There are two layers: High level - pre-packaged constant formatters. Mid level - pattern-based, like SimpleDateFormat. Low level - builder.
Joda-Time uses immutable objects. So rather than change the time zone ("mutate"), we instantiate a new DateTime object based on the old but with the desired difference (some other time zone).
Joda-Time provides support for multiple calendar systems and the full range of time-zones. The Chronology and DateTimeZone classes provide this support. Joda-Time defaults to using the ISO calendar system, which is the de facto civil calendar used by the world.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With