Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joda-Time DateFormatter to display milliseconds if nonzero

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.)

like image 508
Mike Avatar asked May 10 '10 22:05

Mike


People also ask

What is Isodatetimeformat?

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".

What is Joda-Time format?

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.

Does Joda DateTime have timezone?

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).

What is the use of Joda-Time?

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.


1 Answers

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.

like image 123
MetroidFan2002 Avatar answered Sep 25 '22 05:09

MetroidFan2002