开发者

How do I use the time and date format specified in the Android settings?

I would like to开发者_JAVA技巧 use the date and time formats specified in the Android's "Date & Time" settings. Is there an easy way to access this? I looked into the Settings class, however there is no constant that seems to have anything to do with these settings. Any help would be greatly appreciated.


Use DateUtils.formatDateTime()


You can get the specific Format instances that the user specified by using the android.text.format.DateFormat class. With those you just do your normal Java style date formatting.

Unfortunately there's no date AND time Format, so you're going to have to build it by yourself. Or you can use DateUtils.formatDateTime(), as Steve pointed out.


Here's a way to it that's probably more distilled than scanning through applicable bits in an entire example app. This is from my code where I need a locale-formatted date string without the ERA field:

final Date d = new Date();                

DateFormat dateFormat = null;
try {
    dateFormat = DateFormat.getDateInstance(DateFormat.FULL, <context>.getApplication().getLocale());
} catch (NullPointerException npe) {
    dateFormat = DateFormat.getDateInstance(DateFormat.FULL); // Default locale?  Users reported NPEs in the above checked code.
}
StringBuffer formattedDateBuf = new StringBuffer();
FieldPosition eraPos = new FieldPosition(DateFormat.ERA_FIELD);        
StringBuffer formattedDate = dateFormat.format(d, formattedDateBuf, eraPos);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜