我正在研究支持多種語言(英語和西班牙語)的應用程序。我遇到了一個簡單的日期格式對話,當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
}
感謝您的幫助。
也許'字符串time'參數已經改變 – nuvio
你爲什麼不單元測試這一點,改變'getDateTimeInDeviceLocale'參數接受以下'getDateTimeInDeviceLocale(字符串時,布爾is24Hours,區域設置區域)'這將是一個容易得多測試並重現錯誤。 – nuvio
如果星期幾和月份總是英文(例如'Tue'和'Aug'),則在解析 – 2017-08-04 13:34:50