2013-03-06 71 views
0

我有這個示例Java代碼,我想解析一個字符串到日期,基於SimpleDateFormat上設置的模式。當我在JDK6中運行這個代碼時,它的工作正常。但在JDK7中,解析調用返回NULL。任何想法已經被JDK7改變了。這是一個已知的問題或任何解決方法?SimpleDateFormat返回NULL JDK7的日期,但與JDK6工作正常

SimpleDateFormat _theSimpleDateFormatHelper = new SimpleDateFormat(); 
    _theSimpleDateFormatHelper.setLenient(false); 
    _theSimpleDateFormatHelper.applyPattern("yyyy-MM-dd hh:mm:ss"); 

    ParsePosition parsePos = new ParsePosition(0); 
    Object formattedObj = _theSimpleDateFormatHelper.parse("1989-09-21 00:00:00", parsePos); 

回答

1

下面的代碼工作正常:

SimpleDateFormat _theSimpleDateFormatHelper = new SimpleDateFormat(); 
//_theSimpleDateFormatHelper.setLenient(false); <-- In lenient mode, the parsing succeeds 
_theSimpleDateFormatHelper.applyPattern("yyyy-MM-dd hh:mm:ss"); 

ParsePosition parsePos = new ParsePosition(0); 
Object formattedObj = _theSimpleDateFormatHelper.parse("1989-09-21 00:00:00", parsePos); 

它不工作的原因是因爲該格式是嚴格模式不正確。在此頁面http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html中,您可以看到h範圍是1-12。

如果使用H相反,範圍是0-23,這也能發揮作用:

SimpleDateFormat _theSimpleDateFormatHelper = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
_theSimpleDateFormatHelper.setLenient(false); 
Object formattedObj = _theSimpleDateFormatHelper.parse("1989-09-21 00:00:00"); 
相關問題