java.text.ParseException:Unparseable date:" 01/20/2018 12:15 PM" (抵消17)

时间:2018-01-20 07:23:05

标签: android date

实际问题是手机支持的时间格式有a.m.&下午不是AM / PM 1)当哪种手机具有AM / PM格式时,它能正常工作 2)不适用于哪种手机有电话和电话。 P.M。

 String strDate = "01/20/2018 12:15 PM";
    SimpleDateFormat dateF = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
    try {
        Date date = dateF.parse(strDate);
        String convertDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(date);
        tickets.TimeDue = convertDate;
    } catch (ParseException e) {
        e.printStackTrace();
    }

enter image description here

2 个答案:

答案 0 :(得分:0)

这应与您正在使用的区域设置/时区定义相关。

您可以在代码中添加Locale.ENGLISH

更改

SimpleDateFormat dateF = new SimpleDateFormat("MM/dd/yyyy hh:mm a");

SimpleDateFormat dateF = new SimpleDateFormat("MM/dd/yyyy hh:mm a", Locale.ENGLISH);

答案 1 :(得分:0)

unparseable p.m.替换为PM,如下面的代码

 String strDate = "01/20/2018 12:15 p.m.";
    SimpleDateFormat dateF = new SimpleDateFormat("MM/dd/yyyy hh:mm a", Locale.ENGLISH);
    try {
        Date date = null;
        if (strDate.contains("p.m.")){
            strDate = strDate.replace("p.m.","PM");
            date = dateF.parse(strDate);
            String convertDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(date);
             tickets.TimeDue = convertDate;
        }else if(strDate.contains("a.m.")){
            strDate = strDate.replace("a.m.","AM");
            date = dateF.parse(strDate);
            String convertDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(date);

             tickets.TimeDue = convertDate;
        }else {
            date = dateF.parse(strDate);
            String convertDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(date);
            tickets.TimeDue = convertDate;
        }

    } catch (ParseException e) {

        e.printStackTrace();
    }