Je veux parsingr la date dans un format souhaité, mais je reçois une exception à chaque fois. Je sais qu’il est facile à mettre en œuvre mais je suis confronté à un problème. Je ne sais pas où exactement.
Exception: java.text.ParseException: Unparseable date: "2014-06-04" (at offset 5)
Voici mon code:
private Ssortingng getconvertdate(Ssortingng date) { DateFormat inputFormat = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss",Locale.ENGLISH); 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) { // TODO Auto-generated catch block e.printStackTrace(); } Ssortingng outputText = outputFormat.format(parsed); return outputText; }
Entrée dans la méthode: 2014-06-04
Résultats attendus: 6 juin 2014
J’ai suivi des réf. de Stackoverflow.com, mais toujours il problème persiste. S’il vous plaît aider.
Vous n’avez pas de temps dans votre chaîne: et le mois n’a que deux caractères remplacés.
new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss",Locale.ENGLISH);
avec
new SimpleDateFormat("yyyy-MM-dd",Locale.ENGLISH);
// Try this way,hope this will help you to solve your problem.... public Ssortingng convertDateSsortingngFormat(Ssortingng strDate, Ssortingng fromFormat, Ssortingng toFormat){ try{ SimpleDateFormat sdf = new SimpleDateFormat(fromFormat); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); SimpleDateFormat dateFormat2 = new SimpleDateFormat(toFormat.sortingm()); return dateFormat2.format(sdf.parse(strDate)); }catch (Exception e) { e.printStackTrace(); return ""; } }
Peut-être devez-vous vous attaquer à différents formats d’entrée Puis attrapez l’exception de format actuellement non géré (juste un exemple):
private Ssortingng getconvertdate(Ssortingng 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"; } Ssortingng outputText = outputFormat.format(parsed); return outputText; }
Dans mon cas, j’utilisais ::
SimpleDateFormat todaySdf = new SimpleDateFormat("dd MMM yyyy", Locale.ENGLISH);
changé pour
SimpleDateFormat todaySdf = new SimpleDateFormat("dd MM yyyy", Locale.ENGLISH);
et cela a fonctionné .. le M supplémentaire était le coupable !!