2013-04-09 35 views
2

我有4位數的日期。我遇到了2050年以後的投入。在我的申請"0150"意味着January 01 2050。但是,當我格式化它返回下面的輸出。爲什麼格式化日期給上個世紀

Sun Jan 01 00:00:00 PKT 1950 




public static Date getFormatDate(String newformat, String dateValue) throws Exception { 

     try { 

      SimpleDateFormat simpleDateFormat = new SimpleDateFormat(newformat); 
      java.util.Date newdate = simpleDateFormat.parse(dateValue); 
      return newdate; 
     } 
     catch(Exception e) { 
      System.out.println("Exception in converting date format --->" + e); 
      throw e; 
     } 
    } 

    public static void main(String[] args) throws Exception {   
     System.out.println(getFormatDate("MMyy", "0150")); 
    } 

任何幫助解決此問題將不勝感激。

+2

這只是2013年,人們已經試圖再次削減世紀? – CPerkins 2013-04-09 13:07:23

回答

6

根據API documentation,SimpleDateFormat解析兩位數的年份字段,以便結果是「在創建SimpleDateFormat實例之前的80年之內和20年之後」。

如果您想修改行爲以更好地符合您的要求,可以使用方法set2DigitYearStart來設置您的日期映射到的100年期的開始。

5

從SimpleDateFormat的Javadoc中:

對於縮寫年份模式( 「Y」 或 「YY」)解析, 的SimpleDateFormat必須解釋簡稱相對於一些 世紀的年份。它通過將日期調整爲在創建SimpleDateFormat實例之前的 和20年之前的80年內完成。

就你而言,1950年是在今天之前的80年內。

爲了獲得正確的日期(2050),您必須致電SimpleDateFormat.set2DigitYearStart(Date)