Question

I found java.text.DateFormat has 2 methods to format date. One is taking Date parameter, the other taking Object parameter. I checked DateFormat source code and it seems that they call different internal methods.

My question is which method (way) I should use to format Date? WAY 1 vs WAY 2

Here is my code:

 Object dateObject; // This is an instance of java.util.Date

 DateFormat df = this.createDateFormat();

 String formatted1 = df.format ( (Date) dateObject );  // WAY 1

 String formatted2 = df.format ( dateObject );  // WAY 2 -- Calling different internal method.

NOTE that, For WAY 1, I cast dateObject to java.util.Date

Anyone has any ideas? Thanks.

Was it helpful?

Solution

It doesn't matter. The format(Object) is part of the base Format interface; DateFormat also provides a format(Date) for clarity.

Ultimately, the format(Object) version calls DateFormat.format(Object, StringBuffer, FieldPosition) which, from the source, will attempt the following, in order:

  • If object is a Date, cast to Date and perform same conversion as format(Date).
  • If object is a Number, construct a new Date(((Number)object).longValue()) then format that.
  • Otherwise, throw an IllegalArgumentException.

That first point makes format(Object) identical to format(Date) when the object is a Date.

In your case, since date is an Object, I would simply use format(Object) because it is less verbose, and format(Object) will do the cast for you.

OTHER TIPS

Your WAY1 method is from DateFormat class, WAY2 method is from Format class (ancestor of DateFormat). I think both ways calls format method from DateFormat so both ways are equivalent.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top