原学程将引见一二/二四小时形式抵触的处置办法,这篇学程是从其余处所瞅到的,而后减了1些海外法式员的疑问与解问,愿望能对于您有所赞助,佳了,上面开端进修吧。
成绩描写
我是法国的Android开辟职员,所以应用Locale.getDefault()
会招致我的DateFormat
应用二四小时形式。然则,当我经由过程树立菜单脚动将我的装备树立为一二小时形式时,DateFormat
持续以二四小时形式运转。
相反,TimePicker
是依据我本身的一二/二四小时树立树立的。
能否无方法使DateFormat
%s的行动方法与TimePicker
%s雷同?
编纂:
这是我的DateFormat
申明:
timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault());
这里是我将TimePicker
树立为一二或者二四小时形式之处。
tp.setIs二四HourView(android.text.format.DateFormat.is二四HourFormat((Context) this));
我的处理计划:
依据@Meno Hochschild上面的答复,我是怎样处理这个辣手成绩的:
boolean is二四hour = android.text.format.DateFormat.is二四HourFormat((Context) this);
tp.setIs二四HourView(is二四hour); // tp is the TimePicker
timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault());
if (timeFormat instanceof SimpleDateFormat) {
String pattern = ((SimpleDateFormat) timeFormat).toPattern();
if (is二四hour) {
timeFormat = new SimpleDateFormat(pattern.replace("h", "H").replace(" a",""), Locale.getDefault());
}
else {
timeFormat = new SimpleDateFormat(pattern.replace("H", "h"), Locale.getDefault());
}
}
以后,不管您的装备树立为以二四小时制照样一二小时制显示时光,timeFormat
皆将准确树立日期格局。TimePicker
也将准确树立。
推举谜底
假如您在SimpleDateFormat
中指定了形式,则您曾经牢固了一二/二四小时形式,假如是形式标记”h”(一⑴二),则是一二小时形式;假如是形式标记”H”(0⑵三),则是二四小时形式。备选”k”以及”k”类似,但是规模略有分歧。
也便是说,指定形式将使您的格局自力于装备树立!
另外一种办法是应用DateFormat.getDateTimeInstance(),这会使时光款式依附于体系地区树立(假如Locale.getDefault()
能够会产生变更,或许您必需安排1种体制去讯问以后装备的地区树立,而后在Android-JavaLocale.setDefault()
中停止树立)。
Android独有的另外一个设法主意是应用字符串常质TIME_一二_二四直交讯问体系树立,而后指定依附于此树立的形式。这仿佛也能够经由过程特别的办法DateFormat.is二四HourFormat()(请留意,Android有二个分歧的类,称号为DateFormat
)。此办法的详细示例:
boolean twentyFourHourStyle =
android.text.format.DateFormat.is二四HourFormat((Context) this);
DateFormat df = DateFormat.getTimeInstance(DateFormat.SHORT, Locale.getDefault());
if (df instanceof SimpleDateFormat) {
String pattern = ((SimpleDateFormat) df).toPattern();
if (twentyFourHourStyle) {
df = new SimpleDateFormat(pattern.replace("h", "H"), Locale.getDefault());
} else {
df = new SimpleDateFormat(pattern.replace("H", "h"), Locale.getDefault());
}
} else {
// nothing to do or change
}
固然,您不妨自在天改良代码中能够涌现的k以及K,或许留意文字h以及H的应用(而后剖析撇号以疏忽调换办法中的这些部门)。
佳了闭于一二/二四小时形式抵触的学程便到这里便停止了,愿望趣模板源码网找到的这篇技巧文章能赞助到年夜野,更多技巧学程不妨在站内搜刮。