2011-06-02 5 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

答えて

2

何もありません。これは私のコンピュータでうまく動作します。

EDIT:それは役に立たなかった。特定のロケール設定が必要な場合があります。あなたのロケールが異なる月名/曜日名を期待している場合、例外が発生します。

EDIT 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); 
} 
関連する問題