2014-04-28 51 views
1

必須使用SimpleDateFormat解析Java中的日期。我正在使用以StringSimpleDateFormat實例解析它的日期的現有庫。 一切都很好,但如果日期格式只包含自紀元時間(1970年1月1日)以來的毫秒數,即UNIX時間(以毫秒爲單位),則遇到問題。使用new SimpleDateFormat("SS")new SimpleDateFormat("SSS")沒有工作:僅有毫秒的SimpleDateFormat

代碼重現奇怪SimpleDateFormat行爲:

TimeZone.setDefault(TimeZone.getTimeZone("GMT")); // just for the test 
long currTimeInMilli = System.currentTimeMillis(); 

SimpleDateFormat msSDF = new SimpleDateFormat("SS"); // same result with SimpleDateFormat("SSS") 
SimpleDateFormat secSDF = new SimpleDateFormat("ss"); 

System.out.println(msSDF.parse("" + currTimeInMilli)); 
System.out.println(secSDF.parse("" + (currTimeInMilli/1000))); 
System.out.println(new SimpleDateFormat("EEE MMM dd HH:mm:ss zz yyyy").format(currTimeInMilli)); 

產生的輸出:

Mon Dec 15 07:46:20 GMT 1969 <-- should be like two other lines (?)! 
Mon Apr 28 20:55:19 GMT 2014 <-- OK 
Mon Apr 28 20:55:19 GMT 2014 <-- OK 

它是正常的嗎?我怎樣才能設置一個SimpleDateFormat能夠解析自時代以來經過的毫秒數?

注:

  • 我不能用到其他庫一樣喬達時間
  • 我不能用new Date(long pNbMilli)構造日期(傳統圖書館正在採取SimpleDateFormat實例作爲輸入)
  • 我發現這filed JDK bug但不知道它是直接綁定到這個問題...
+0

並且沒有日曆允許? –

+0

@Rod_Algonquin no::( – xav

回答

5

T他S模式將不會正確處理大於Integer.MAX_VALUE的毫秒數,正如對於通常表示爲長的數量看起來那樣奇怪。

如果你真的必須使用現有的API,它需要一個日期格式,你總是可以破解它:

SimpleDateFormat msSDF = new SimpleDateFormat("SSS") { 

      @Override 
      public Date parse(String source) throws ParseException { 
       return new Date(Long.parseLong(source)); 
      } 

}; 

(可能還需要提供format(string)砍死的實現過於依賴於你的遺留API實際上沒有當然。)

+0

謝謝。好主意。那麼不應該將它作爲'SimpleDateFormat'中的錯誤報告嗎? – xav