2016-01-04 265 views
0

我想以“dd MMM yyyy”格式显示日期。我输入的日期有时 2015年12月30日19时57分15秒,有些情况下是2015年12月30日11:59:20android:更改日期格式

我有代码给第二种情况的错误。 我怎样才能做到这一点在这种方式它处理日期在任何形式或任何其他新的格式

DateFormat toFormat = new SimpleDateFormat("dd MMM yyyy"); 
    toFormat.setLenient(false); 
    Date date = null; 
    try { 
     date = toFormat.parse(dateSent); 
     date = toFormat.parse("Dec 30, 2015 11:59:20 AM"); 
    } catch (ParseException e) { 
     e.printStackTrace(); 
    } 
+0

如果(dateSent.indexOf(”“) > = 3){Dec 30} else {30 Dec} –

回答

1

你可以这样做:

/** 
    * Convert Date from-to Format 
    * 
    * @param date 
    * @return 
    */ 
    public static String convertDate(String date, String fromFormat, String toFormat) { 
     try { 
      return new SimpleDateFormat(toFormat, Locale.ENGLISH).format(new SimpleDateFormat(fromFormat, Locale.ENGLISH).parse(date)); 
     } catch (Exception e) { 
      Log.e(TAG, "Date Converting " + date + " : " + e.getLocalizedMessage()); 
     } 
     return ""; 
    } 
0
DateFormat toFormat = new SimpleDateFormat("dd MMM yyyy"); 
DateFormat toFormat1 = new SimpleDateFormat("MMM dd yyyy"); 
toFormat.setLenient(false); 
Date date = null; 
try { 
    date = toFormat.parse(dateSent); 
} catch (ParseException e) { 
    e.printStackTrace(); 
} 
if(date == null){ 
    try { 
     date = toFormat1.parse(dateSent); 
    } catch (ParseException e) { 
     e.printStackTrace(); 
    } 
} 
return date;