2016-03-28 125 views
-3

我有一個要求,我將日期轉換爲一種格式到另一個,我可以得到一個不可解析的日期異常。該類的代碼如下Java日期解析異常

public class DateTester { 

    public static void main(String[] args) { 
     // TODO Auto-generated method stub 

     String stringDate = "Fri Feb 26 14:14:40 CST 2016"; 
     Date date = convertToDate(stringDate); 
     System.out.println(date); 
    } 

    public static Date convertToDate(String date) { 
     SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy"); 
     Date convertedCurrentDate = null; 
     try { 
      convertedCurrentDate = sdf.parse(date); 
     } catch (ParseException e) { 
      // TODO Auto-generated catch block 
      System.out.println(e.getMessage()); 
     } 
     return convertedCurrentDate; 
    } 
} 
+1

首先,您需要從String創建/解析Date對象,然後將日期對象轉換爲String或任何您想要的。 – kosa

+0

你的stringDate格式和解析格式不一樣。請參閱:https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html – kevingreen

+1

'「星期五Feb 26 14:14:40 CST 2016」'看起來不像它有一個'MM-dd-yyyy'的格式' – Bohemian

回答

1

使用粘貼此格式:

SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy"); 

代碼:

public class StackOverflowSample { 
    public static void main(String[] args) { 
     String stringDate = "Fri Feb 26 14:14:40 CST 2016"; 
     Date date = convertToDate(stringDate); 
     System.out.println(date); 
    } 

    public static Date convertToDate(String date) { 
     SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy"); 
     Date convertedCurrentDate = null; 
     try { 
      convertedCurrentDate = sdf.parse(date); 
     } catch (Exception e) { 
      System.out.println(e.getMessage()); 
     } 
     return convertedCurrentDate; 
    } 
} 

來源:https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

編輯:如果你想返回日期格式爲「MM-dd-yyyy」的字符串

public static void main(String[] args) { 
    String stringDate = "Fri Feb 26 14:14:40 CST 2016"; 
    Date date = convertToDate(stringDate); 
    SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy"); 
    String dateFormatted = sdf.format(date); 
    System.out.println(dateFormatted); 
} 
+0

這隻打印日期作爲輸入,我希望輸出日期爲m/dd/yyyy格式 – developer2015