Android:简单日期格式解析异常

时间:2016-07-04 06:51:27

标签: android datetime simpledateformat parseexception

我正在尝试使用简单日期格式来更改数据,但我得到了解析异常

java.text.ParseException: Unparseable date: "11/08/2016 02:00:00 PM" (at offset 20)
at java.text.DateFormat.parse(DateFormat.java:579)

我的输入日期是“11/08/2016 02:00:00 PM”

SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss aa",Locale.getDefault());
try
{
  expiryDate = df.parse(mPayRespo.get(position).getVoucherExpDate());
}
catch(ParseException pe){
             pe.printStackTrace();
}

在我的设置中,日期和时间设置为自动。我只在SAMASUNG S6中遇到这个问题

任何人都可以帮助我

3 个答案:

答案 0 :(得分:1)

试试此代码Convert 12 Hour date/time format to 24 hour date/time format

String input = "23/12/2014 10:22:12 PM";
  //Format of the date defined in the input String
  DateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss aa");
  //Desired format: 24 hour format: Change the pattern as per the need
  DateFormat outputformat = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
  Date date = null;
  String output = null;
  try{
     //Converting the input String to Date
     date= df.parse(input);
     //Changing the format of date and storing it in String
     output = outputformat.format(date);
     //Displaying the date
     System.out.println(output);
  }catch(ParseException pe){
     pe.printStackTrace();
   }
  

输出

12-23-2014 22:22:12

这应该有效。

答案 1 :(得分:1)

三星设备中出现日期时间解析异常,因为它们的12小时格式为上午/下午而不是AM / PM。尝试我找到的解决方案解决方案:

 public Date getDateFormatCrntDateTime(String date) throws ParseException {
        String AMPM=date.substring(19);
        String hour=date.substring(11,13);
        Log.e(TAG,"AM PM is: "+AMPM);
        Log.e(TAG," Hour is: "+hour);

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH : mm");
    Date currentDate=df.parse(date);
    Log.w(TAG,"date of device before format is: "+currentDate);

    if (AMPM.equalsIgnoreCase("AM")) {
        if (hour.equalsIgnoreCase("12")) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(currentDate);
            calendar.add(Calendar.HOUR_OF_DAY, -12);
            currentDate = calendar.getTime();
        }
    }
    if (AMPM.equalsIgnoreCase("PM")){
        if (hour.equalsIgnoreCase("12")){
        }
        else{
            Calendar cal=Calendar.getInstance();
            cal.setTime(currentDate);
            cal.add(Calendar.HOUR_OF_DAY,12);
            currentDate=cal.getTime();
        }

    }
    Log.e(TAG,"Date of device is: "+currentDate);
    return currentDate;
}

相应地更改简单日期格式和子字符串

答案 2 :(得分:0)

应该是

SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a",Locale.getDefault());

注意a而不是aa

相关问题