Question: I'm looking for a clean solution for formatting [Date](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html) objects with optional parts. My date object can be a timestamp value, a time-only value or a date-only value.

### Expected output

I would like to display the date value like this:

If the date's [ms value](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html#getTime--) is less than (86400\*1000) then it means the value is a really a time-only value. If so display like this:

```
HH:mm:ss.SSS

```

If the date's value is exactly at midnight then it means it is a date-only value. If so display like this:

```
yyyy-MM-dd

```

Otherwise display like this:

```
yyyy-MM-dd HH:mm:ss.SSS

```

### Solution constraints

Unfortunately I'm working with `Date` as the input. Can't be changed. I'm only interested in formatting/rendering, not in parsing. External libraries are a hard sell in my organization.

For the purpose of formatting it would of course be acceptable to first convert to one of new Java 8 date/time objects if that will make the solution simpler.

Platform : Java 8 SE

Answer: 
Instead of `java.util.Date` use the appropriate class in the `java.time` package. This means you can explicitly have separate methods for your `LocalDate`, `LocalTime` or `LocalDateTime`, and it makes the code cleaner.

Now, if you're stuck with a `java.util.Date` and there's nothing you can do about it, you should use the `getTime()` method (which you already know about) to decide among various [`SimpleDateFormat`](https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html) implementations for each of your output types.
I think you need multiple SimpleDateFormat objects for it. Your code may look like this:

```
SimpleDateFormat timeOnlySdf = new SimpleDateFormat( "HH:mm:ss.SSS");
SimpleDateFormat dateOnlySdf = new SimpleDateFormat( "yyyy-MM-dd");
SimpleDateFormat dateAndTimeSdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss.SSS");

Date epochPlusOne = new Date( 86400 * 1000);
Calendar cal = Calendar.getInstance();
cal.setTime( myDate);

if( myDate.before( epochPlusOne))
{
    System.out.println( timeOnlySdf.format( myDate));
}
else if( cal.get( Calendar.HOUR) == 0 && 
        cal.get( Calendar.MINUTE) == 0 && 
        cal.get( Calendar.SECOND) == 0 && 
        cal.get( Calendar.MILLISECOND) == 0)
{
    System.out.println( dateOnlySdf.format( myDate));
}
else
{
    System.out.println( dateAndTimeSdf.format( myDate));
}

```