Aeefire
Aeefire

Reputation: 938

DateFormat Android - properly?

I am wondering how to properly display dates in Android. I mean date-formats, which fit to the specific region, where the application is downloaded. What I am doing atm is:

DateFormat formatter = DateFormat.getDateTimeInstance();
String[] dateParts = date.split(DATE_DELIMITER);
Date temp = new Date(Integer.valueOf(dateParts[4])-1900, Integer.valueOf(dateParts[3]),
            Integer.valueOf(dateParts[2]), Integer.valueOf(dateParts[0]),
            Integer.valueOf(dateParts[1]));
return formatter.format(temp);

So... There are following problems with this: Java.util.Date is marked as deprecated, and it displays me seconds too, although I don't want that.

Is there any "Beautiful" solution for that? I'd be glad if you could tell me :)

Upvotes: 2

Views: 4637

Answers (2)

Mr.Me
Mr.Me

Reputation: 9276

Android DateFormat Using Device Current Locale

In android you can use the device's locale while formatting your date object by doing this:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss", Locale.getDefault())
String formatedText = sdf.format(new Date());

Edit

To use the exact system Date Formates use:

        DateFormat.getDateFormat(mContext).format(new Date());

Upvotes: 2

RMalke
RMalke

Reputation: 4094

EDIT

To format a date for the current Locale, use one of the static factory methods:

String formattedString = DateFormat.getDateInstance().format(yourDate);

This will format accordingly to the device current locale, that is the one configured in android settings.

More Info


A solution is to use a SimpleDateFormat

public static vod FormatDate(Date yourDate) {

    SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");

    return sdf.format( yourDate ));

}

Related: Android SimpleDateFormat, how to use it?

Upvotes: 5

Related Questions