
相反,TimePickers根据我自己的12/24小时设置进行设置.
有没有办法让DateFormats的行为与TimePickers相同?
编辑:
这是我的DateFormat声明:
timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT,Locale.getDefault());
这里是我设置TimePickerto 12或24小时模式的地方.
tp.setIs24HourVIEw(androID.text.format.DateFormat.is24HourFormat((Context) this));
我的解决方案
根据@Meno Hochschild在下面的回答,这是我如何解决这个棘手的问题:
boolean is24hour = androID.text.format.DateFormat.is24HourFormat((Context) this);tp.setIs24HourVIEw(is24hour); // tp is the TimePickertimeFormat = DateFormat.getTimeInstance(DateFormat.SHORT,Locale.getDefault());if (timeFormat instanceof SimpleDateFormat) { String pattern = ((SimpleDateFormat) timeFormat).topattern(); if (is24hour) { timeFormat = new SimpleDateFormat(pattern.replace("h","H").replace(" a",""),Locale.getDefault()); } else { timeFormat = new SimpleDateFormat(pattern.replace("H","h"),Locale.getDefault()); }} 在此之后,timeFormat将正确格式化日期,无论您的设备是以24小时格式还是以12小时格式显示时间. TimePicker也将正确设置.
解决方法 如果您在SimpleDateFormat中指定了一个模式,那么您已经修复了12/24小时模式,在模式符号“h”(1-12)的情况下为12小时模式,在模式符号的情况下为24小时模式“H”(0-23).替代“k”和“K”类似,范围略有不同.也就是说,指定一个模式会使您的格式与设备设置无关!
另一种方法是使用DateFormat.getDateTimeInstance(),它使时间样式依赖于系统区域设置(如果Locale.getDefault()可能会更改 – 或者您必须部署一种机制,如何询问当前设备区域设置,然后在AndroID-Java Locale中设置.默认设置()).
AndroID的另一个想法是使用字符串常量TIME_12_24直接询问系统设置,然后指定依赖于此设置的模式.这似乎也可以通过特殊方法DateFormat.is24HourFormat()(请注意,AndroID有两个不同的类,名称为DateFormat).这种方法的具体例子:
boolean twentyFourHourStyle = androID.text.format.DateFormat.is24HourFormat((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",Locale.getDefault()); }} else { // nothing to do or change} 您当然可以自由地为可能出现的k和K细化代码,或者注意使用文字h和H(然后解析叛逆者在替换方法中忽略这些部分).
总结以上是内存溢出为你收集整理的android – 12/24小时模式冲突全部内容,希望文章能够帮你解决android – 12/24小时模式冲突所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)