user1545072
user1545072

Reputation:

What is the difference between SimpleDateFormat and android.text.format.DateFormat?

From reading about them I understand that the android class is a utility class made for convenience only, and provide nothing that SimpleDateFormat doesn't provide. Is there any significance to the android class? Is it better practice to use it (if yes, why)? My goal is to display a Date object in an android app (obviously). Here it is:

private Date date;

public String getDateString(String formatStr){
    return new SimpleDateFormat(formatStr).format(date);
}

would it be better to use android.text.format.DateFormat like this:

public String getDateString(String formatStr){
    return android.text.format.DateFormat.format(formatStr, date);
}

or perhaps none of the two, but a different way would be best? thanks in advance.

Upvotes: 6

Views: 8734

Answers (2)

benkc
benkc

Reputation: 3382

Copying my answer from https://stackoverflow.com/a/27116266/642160 :

As far as I can tell, android.text.format.DateFormat has some of the functionality from java.text.DateFormat, some of the functionality from java.text.SimpleDateFormat, and some extra functionality of its own.

Most notably:

  • The java SimpleDateFormat allows construction of arbitrary non-localized formats.
  • The java DateFormat allows construction of three localized formats each for dates and times, via its factory methods.
  • The android DateFormat allows most of the above (arbitrary formats and a smaller number of localized formats), but also provides getBestDateTimePattern which picks a locale-appropriate format string that contains the elements specified with locale-appropriate ordering and punctuation.

So, if you need a localized date/time format other than the three provided by java's DateFormat class, the android DateFormat class is the solution.

Less importantly, but an additional convenience: the android DateFormat methods can take a Calendar or long milliseconds directly, instead of requiring a Date object. I always prefer working with Calendar or long over Date. Also, it properly respects the timezone of the Calendar object -- whereas getting a Date from a Calendar and passing that along to the formatter loses the timezone information. (Nothing you can't get around via java DateFormat's setCalendar method, but it's nice to not have to.)

Finally, and least importantly, some of the methods of the Android DateFormat don't actually construct a formatter, you just construct a format string. All of this class's methods are static. The methods do that construct a DateFormat actually construct a java DateFormat!

Upvotes: 4

user1545072
user1545072

Reputation:

I believe the answer lies here:

This class' factory methods return appropriately-localized DateFormat instances, suitable for both formatting and parsing dates.

I don't think the SimpleDateFormat provide appropriately-localized formats.

Upvotes: 1

Related Questions