SimpleDateFormat不适用于7.0及以上版本
我正在研究支持多种语言(英语和西班牙语)的应用程序。我遇到了一个简单的日期格式对话,当Locale = es时,它只会在Android 7.0和更高版本上失败。SimpleDateFormat不适用于7.0及以上版本
这很奇怪,因为相同的代码在6.0和以前的SDK版本上工作得非常好。我也检查了https://developer.android.com/guide/topics/resources/multilingual-support.html 这并没有太大的帮助。
这是代码
public String getDateTimeInDeviceLocale(Context context, String time) {
String output = "";/*Tue, 27 Aug 2013 18:10:00 Z*/
SimpleDateFormat utcFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'Z'", Locale.getDefault());
utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
if (null != time) {
Date date = new Date();
date = utcFormat.parse(time); //Throws exception only on Espanol
SimpleDateFormat format;
if (is24HourFormat(context)) {
format = new SimpleDateFormat("EEE MMM dd, yyyy HH:mm", Locale.getDefault());
}else {
format = new SimpleDateFormat("EEE MMM dd, yyyy hh:mm aa", Locale.getDefault());
}
output = format.format(date);
String timeZoneName = TimeZone.getDefault().getDisplayName(
TimeZone.getDefault().inDaylightTime(new Date()),
TimeZone.SHORT);
if (!TextUtils.isEmpty(timeZoneName)) {
output = output + " " + timeZoneName;
}
}
} catch (ParseException e) {
// Unparseable date
}
感谢您的帮助。
我测试,似乎没什么问题,检查应用程序
@Test
public void testGetDatetimeInDeviceLocale_en() throws ParseException{
Locale english = Locale.ENGLISH;
SimpleDateFormat utcFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'Z'", english);
String testableDate = utcFormat.format(new Date(0));
// test 24 hours format
assertEquals("Thu Jan 01, 1970 02:00 BST", getDateTimeInDeviceLocale(true, testableDate, english));
// test AM PM format
assertEquals("Thu Jan 01, 1970 02:00 AM BST", getDateTimeInDeviceLocale(false, testableDate, english));
}
@Test
public void testGetDatetimeInDeviceLocale_es() throws ParseException{
Locale spanish = Locale.forLanguageTag("es");
SimpleDateFormat utcFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'Z'", spanish);
String testableDate = utcFormat.format(new Date(0));
// test 24 hours format
assertEquals("jue ene 01, 1970 02:00 BST", getDateTimeInDeviceLocale(true, testableDate, spanish));
// test AM PM format
assertEquals("jue ene 01, 1970 02:00 AM BST", getDateTimeInDeviceLocale(false, testableDate, spanish));
}
附注的其他领域正如我在评论上述建议你应该你的方法签名更改为以下:
public String getDateTimeInDeviceLocale(boolean is24Hours, String time, Locale locale) throws ParseException
P.P.S我已删除你钓到的鱼,让异常抛出以获得错误的反馈。
时必须使用'Locale.ENGLISH'而不是'getDefault()'。正如我的问题所述,它只会失败在Android 7.0及以上版本,当选择的语言不是en_US(在我的情况下是西班牙语) –
它与Locale有关 –
也许'字符串time'参数已经改变 – nuvio
你为什么不单元测试这一点,改变'getDateTimeInDeviceLocale'参数接受以下'getDateTimeInDeviceLocale(字符串时,布尔is24Hours,区域设置区域)'这将是一个容易得多测试并重现错误。 – nuvio
如果星期几和月份总是英文(例如'Tue'和'Aug'),则在解析 – 2017-08-04 13:34:50