Wrong arguments for DateFormat.format()


#1

In Listing 21.4, it has

But I get an error for .format() saying I’m providing the wrong type of arguments (which in this case is a String and a Date), and looking up documentation for the DateFormat class, there’s three instances of format():

String format(Date date)
abstract StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition)
StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition fieldPosition)

Has anyone found a workaround to this line of code? In the meantime, I’ve just been using “String format(Date date)” instead of what is shown in Listing 21.4


#2

There are actually two classes called DateFormat - java.text.DateFormat and android.text.format.DateFormat. You want the latter one, not the standard Java one.


#3

I could not get it to work either. So i have changed it into:

SimpleDateFormat simpleFormat = new SimpleDateFormat("EEEE, MMM dd"); String dateString = simpleFormat.format(mCrime.getDate());


#4

Creating new instances of SimpleDateFormat every time you need to format a date can get very expensive. You can fix this by only creating one instance and sharing it, but then you run into another problem - SimpleDateFormat is not threadsafe.

Both of these problems are solveable, but this is why we recommend using android.text.format.DateFormat.format(…) method instead for simple formatting. I promise that it works fine. :slight_smile: