2012-08-08 76 views
3

我使用SimpleDataFormat多年。我從來沒有得到這個ExceptionJava:SimpleDataFormat解析時拋出異常

程序是下面,我從網上得到一個例子驗證碼:

public static void main(String[] args) { 
    // Make a new Date object. It will be initialized to the 
    // current time. 
    Date now = new Date(); 

    // Print the result of toString() 
    String dateString = now.toString(); 
    System.out.println(" 1. " + dateString); 

    // Make a SimpleDateFormat for toString()'s output. This 
    // has short (text) date, a space, short (text) month, a space, 
    // 2-digit date, a space, hour (0-23), minute, second, a space, 
    // short timezone, a final space, and a long year. 
    SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy"); 

    // See if we can parse the output of Date.toString() 
    try { 
     Date parsed = format.parse(dateString); 
     System.out.println(" 2. " + parsed.toString()); 
    } 
    catch(ParseException pe) { 
     System.out.println("ERROR: Cannot parse \"" + dateString + "\""); 
    } 

    // Print the result of formatting the now Date to see if the result 
    // is the same as the output of toString() 
    System.out.println(" 3. " + format.format(now)); 
} 

好很簡單。

結果:

1. Wed Aug 08 13:49:05 BRT 2012 
    ERROR: Cannot parse "Wed Aug 08 13:49:05 BRT 2012" 
3. Qua Ago 08 13:49:05 BRT 2012 

你看到2引發的錯誤?對我而言,這一切都是正確的。

我應該設置哪些區域設置?

我O.S:Windows 7的業餘體校,Service Pack 1的 JDK:jdk1.6.0_25

+0

是的,我差點沒有進入這裏。我會做的... – felipe 2012-08-08 17:38:32

回答

9

它看起來就像是一個語言環境的問題,是的。如果你看看輸出,它不會使用英文的月份和日期名稱 - 所以它也不能解析它們。嘗試指定英文,當你創建SimpleDateFormat

SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", 
               Locale.US);