How do I display time in 24-hour format using a TextClock?

littledevils326 picture littledevils326 · Mar 12, 2013 · Viewed 30.6k times · Source

I am having trouble trying to get a time to display in 24-hour format. I have got it to display the time in another time zone but I can't get it to display in 24-hour format.

<TextClock
    android:id="@+id/hk_time"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:timeZone="GMT+0800"
    android:format24Hour="MMM dd, yyyy k:mm" />

Also is it possible to display a date using a TextClock?

Answer

Michael Scheper picture Michael Scheper · Feb 20, 2014

If your system is in 12-hour mode, you shouldn't have to write a subclass to get what you want. The JavaDocs say:

  • In 12-hour mode:
    • Use the value returned by getFormat12Hour() when non-null
    • Otherwise, use the value returned by getFormat24Hour() when non-null
    • Otherwise, use a default value appropriate for the user's locale, such as HH:mm

Therefore, I would expect the last line in this to make getFormat12Hour() return null and thus use your custom getFormat24Hour() format:

<android.widget.TextClock
    android:id="@+id/hk_time"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:timeZone="GMT+0800"
    android:format24Hour="MMM dd, yyyy k:mm"
    android:format12Hour="@null" />

(BTW, as others have mentioned, forced formats should be used with care. If your users wanted a 24-hour clock, they would have specified this in their system preferences. And apps that force numerically formatted, topsy-turvy date formats on their users, like MM/dd/yyyy, invite one-star ratings (except, in this case, from US and Filipino users), so it's a good thing you're using MMM! You'd still be better off using getBestDateTimePattern(), though, which, I believe, would require subclassing TextClock.)