问题
I'm currently building my first app for Android. What I'm having trouble with is the storage and localized display of dates in connection with a SimpleCursorAdapter
. I have a class that encapsulates access to an SQLitedatabase
with three tables. This class takes care of storing all dates in ISO format ("yyyy-MM-dd"). When the date values are read from the database and displayed on the screen I want them to be formatted in a localized format. Here's the approach I've come up with. It uses a ViewBinder
to do the formatting:
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
@Override
public boolean setViewValue(View view, Cursor cursor,
int columnIndex) {
if (view.getId() == R.id.text1) {
((TextView) view).setText(getDateFormatView().format(
parseDatabaseDate(cursor.getString(columnIndex))));
return true;
} else if (view.getId() == R.id.text2) {
((TextView)view).setText(
cursor.getString(columnIndex));
return true;
} else {
return false;
}
}
});
getDateFormatView()
creates a SimpleDateFormat
object with a pattern that is read from strings.xml
. parseDatabaseDate()
does the parsing of the date from the database with a SimpleDateFormat
that is constructed using a constant pattern yyyy-MM-dd
.
Although this code works just fine I'm wondering if there is a better way to do that. What I don't like is that I need:
- two
SimpleDateFormat
objects (one is used inparseDatabaseDate()
in order to parse the date string from theSQLiteDatabase
, the other is used to format the value) - a
java.util.Date
object that is created then thrown away immediately - quite a lot of (in my opinion) boilerplate code.
So that's why I'm asking: is there a better way to display dates in localized format?
回答1:
If you want to skip on the parsing, you could store the date as a long instead. Then you could just create a new Date object using the long with zero parsing.
This isn't directly related to your question, but: One thing you might want to consider using is android.text.format.DateFormat for getting your date formatters. This way you format your dates/times to the user's locale settings instead of your own presets. It might also make your code simpler, as you don't need to create your own SimpleDateFormat anymore.
With these two things in mind, you can get rid of the calls to your own methods:
((TextView) view).setText(android.text.format.DateFormat.getDateFormat().format(new Date(cursor.getString(columnIndex))));
来源:https://stackoverflow.com/questions/2117565/displaying-dates-in-localized-format-on-android