2011-06-02 25 views
1

我的代碼在下面出現了什麼問題?使用SimpleDateFormat將自定義日期格式轉換爲另一個時出錯

try { 

    // dataFormatOrigin (Wed Jun 01 14:12:42 2011) 
    // this is original string with the date information 

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

    Date date = sdfSource.parse(dataFormatOrigin); 

    // (01/06/2011 14:12:42) - the destination format that I want to have 

    SimpleDateFormat sdfDestination = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); 

    dataFormatDest = sdfDestination.format(date); 

    System.out.println("Date is converted to MM-dd-yyyy hh:mm:ss"); 

    System.out.println("Converted date is : " + dataFormatDest); 

} catch (ParseException pe) { 
    System.out.println("Parse Exception : " + pe); 
} 
+1

您告訴我們,什麼是錯的:發生了什麼? – trutheality 2011-06-02 23:43:13

回答

2

沒有。這在我的電腦上工作得很好。

編輯:這沒有幫助。您可能需要考慮特定的區域設置。如果您的區域設置期望不同的月份名稱/日期名稱,您將得到一個例外。

編輯2:試試這個:

try{ 
     String dataFormatOrigin = "Wed Jun 01 14:12:42 2011"; 
     // this is original string with the date information 
     SimpleDateFormat sdfSource = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy", Locale.US); 

     Date date = sdfSource.parse(dataFormatOrigin); 

     // (01/06/2011 14:12:42) - the destination format that I want to have 
     SimpleDateFormat sdfDestination = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss"); 

     String dataFormatDest = sdfDestination.format(date); 

     System.out .println("Date is converted to MM-dd-yyyy hh:mm:ss"); System.out .println("Converted date is : " + dataFormatDest); 

    } catch (ParseException pe) { 
     System.out.println("Parse Exception : " + pe); 
     pe.printStackTrace(); 
    } 
2

這應該工作:

try { 

    // dataFormatOrigin (Wed Jun 01 14:12:42 2011) 
    // this is original string with the date information 



    // (01/06/2011 14:12:42) - the destination format 
    SimpleDateFormat sdfDestination = new SimpleDateFormat(
    "dd-MM-yyyy hh:mm:ss"); 

    sdfDestination.setLenient(true); 
    //^Makes it not care about the format when parsing 

    Date date = sdfDestination.parse(dataFormatOrigin); 

    dataFormatDest = sdfDestination.format(date); 

    System.out 
    .println("Date is converted to MM-dd-yyyy hh:mm:ss"); 

    System.out 
    .println("Converted date is : " + dataFormatDest); 


} catch (ParseException pe) { 
    System.out.println("Parse Exception : " + pe); 
} 
相關問題