java.text.ParseException: Unparseable date: “2014-06-04” (at offset 5)

后端 未结 4 1779
名媛妹妹
名媛妹妹 2021-01-04 19:14

I want to parse the date into a desired format but i am receiving an exception every time. i know it is easy to implement but i am facing some problem don\'t know where exac

相关标签:
4条回答
  • 2021-01-04 19:27
    // Try this way,hope this will help you to solve your problem....
    
    public String convertDateStringFormat(String strDate, String fromFormat, String toFormat){
           try{
              SimpleDateFormat sdf = new SimpleDateFormat(fromFormat);
              sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
              SimpleDateFormat dateFormat2 = new SimpleDateFormat(toFormat.trim());
              return dateFormat2.format(sdf.parse(strDate));
           }catch (Exception e) {
              e.printStackTrace();
              return "";
           }
    }
    
    0 讨论(0)
  • 2021-01-04 19:27

    Maybe you need to tackle different input formats Then catch the currently unmanaged format exception (just a sample):

    private String getconvertdate(String date) {
        System.out.println(date.length());
        DateFormat inputFormat = null;
                if(date.length() == 20)
                    inputFormat = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss",Locale.ENGLISH);
        if(date.length() == 10)
            inputFormat = new SimpleDateFormat("yyyy-MM-dd",Locale.ENGLISH) ;
    
        if(null == inputFormat)
            return "Format invalid";
    
        inputFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        DateFormat outputFormat = new SimpleDateFormat("dd-MMM-yyyy",Locale.ENGLISH);
        Date parsed = null;
        try {
            parsed = inputFormat.parse(date);
        } catch (ParseException e) {
            return "Input Date invalid";
        }
        String outputText = outputFormat.format(parsed);
        return outputText;
    }
    
    0 讨论(0)
  • 2021-01-04 19:32

    In my case, I was using ::

    SimpleDateFormat todaySdf = new SimpleDateFormat("dd MMM yyyy", Locale.ENGLISH);
    

    changed it to

    SimpleDateFormat todaySdf = new SimpleDateFormat("dd MM yyyy", Locale.ENGLISH);
    

    and it worked.. the extra M was the culprit !!

    0 讨论(0)
  • 2021-01-04 19:33

    You have no time part in your string: and the Month has only two character replace

    new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss",Locale.ENGLISH);
    

    with

    new SimpleDateFormat("yyyy-MM-dd",Locale.ENGLISH);
    
    0 讨论(0)
提交回复
热议问题