Android 无法解析日期:2017 年 1 月 6 日

Android Unparsable Date : Jan 06, 2017

我使用的函数是

public static String getFormatedDate(String dateVal) {
    String tempDate = null;
    Locale systemLocale = Locale.getDefault();

    try {
        SimpleDateFormat formatter = new SimpleDateFormat("MMM dd, yyyy",
                systemLocale);
        Date date = (Date) formatter.parse(dateVal);
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
        tempDate = sdf.format(date);

    } catch (Exception e) {
        ApplicationLog.log(TAG, e);
    }

    return tempDate;
}

在许多设备中,此功能可以正常工作,但在其中一个设备中,解析日期时会引发异常。此异常是否与 Locale.getDefault() 有关?如果是,我应该做什么改变?谢谢。

调用函数

Utilities.getFormatedDate(date);

例外是...

Utilities:java.text.ParseException: Unparseable date: "Jan 06, 2017" (at offset 0)
at java.text.DateFormat.parse(DateFormat.java:579) 

您正在尝试从区域设置相关格式解析日期 "MMM dd, yyyy" 并设置系统区域设置。尝试传递符合您的格式的语言环境。例如 Locale.US。像这样改变你的方法,

public static String getFormatedDate(String dateVal) {
    String tempDate = null;

    try {
        SimpleDateFormat formatter = new SimpleDateFormat("MMM dd, yyyy",
                Locale.US);
        Date date = (Date) formatter.parse(dateVal);
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
        tempDate = sdf.format(date);

    } catch (Exception e) {
        ApplicationLog.log(TAG, e);
    }

    return tempDate;
}