SimpleDateFormat不适用于7.0及更高版本

时间:2017-07-31 13:26:54

标签: android simpledateformat

我正在开发支持多语言(英语和西班牙语)的应用程序。我坚持使用简单的日期格式对话,只有当Locale = es时才会在Android 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
    }

感谢您的帮助。

1 个答案:

答案 0 :(得分:-1)

我对它进行了测试,对我来说似乎很好,请查看应用程序的其他区域

@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));
}

P.S。正如我在上面的评论中所建议的那样,您应该将方法签名更改为以下内容:

public String getDateTimeInDeviceLocale(boolean is24Hours, String time, Locale locale) throws ParseException

P.P.S我删除了你的捕获并让异常被抛出以获得错误反馈。

相关问题