I would like to create a locale sensitive string (for presentation in
the UI) *generally* looking like:

dd/mm/yyyy hh:mm:ss a
or
yyyy/mm/dd HH.mm.ss

I want the numeric date format set by the user in Settings (mm/dd/YYYY
or YYYY/mm/dd), and time is either 12 or 24 hour time format as
specified in Settings also.

Android has several helper classes, for this, but none seem to fully
meet my criteria.

* java.DateFormat.createDateTimeInstance() : produces localized
formats, but ignores what user has set for numeric date format and
12/24 format in Settings.

* android.text.format.DateUtils.formatDateTime() : does not print
seconds

* android.text.format.DateFormat.getTimeFormat() : does not include
seconds

One hackish approach might be to use getTimeFormat, cast it back to a
SimpleDateFormat, and use toPattern() and some magic to add ':ss' to
the pattern, but this is gross and we don't really know what the
localized separator is anyhow.

So I have the following code, which seems rather ugly, but fixes the
time into a non-localized format:

// Get date format as specified in Settings
DateFormat dateFormat =
android.text.format.DateFormat.getDateFormat(context);

boolean is24HourFormat =
android.text.format.DateFormat.is24HourFormat(context);
String timePattern = context.getString(is24HourFormat ?
R.string.twenty_four_hour_time_format :
R.string.twelve_hour_time_format);

// Get 12 or 24 hour time format using timePattern
DateFormat timeFormat = new SimpleDateFormat(timePattern);

Date now = new Date();

return dateFormat.format(date) + ", " + timeFormat.format(date);

With my own format strings:
<string name="twelve_hour_time_format">h:mm:ss a</string>
<string name="twenty_four_hour_time_format">HH:mm:ss</string>

This seems like a huge mess, is there a better way to do this? Notice
I had to provide my own template, but they are not localized for every
locale.

-- 
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to android-developers@googlegroups.com
To unsubscribe from this group, send email to
android-developers+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en

Reply via email to