2012-03-17 61 views
4

我已經創建了幾個SimpleDateFormat的子類來簡化處理我在Android上談論的Azure feed。其中之一是:SimpleDateFormat子類添加了1900年到年

public class ISO8601TLDateFormat extends SimpleDateFormat { 

    private static String mISO8601T = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"; 

    public ISO8601TLDateFormat() { 
     super(mISO8601T); 
    } 

    public ISO8601TLDateFormat(Locale inLocale) { 
     super(mISO8601T, inLocale); 
    } 
} 

正如你所看到的意圖是產生或解釋日期看起來像

2012-03-17T00:00:00.000 + 0100

這是什麼Azure服務期待。然而,當我在從DatePicker如此構造Date對象飼料:

mDate = new Date(mDatePicker.getYear(), mDatePicker.getMonth(), mDatePicker.getDayOfMonth()); 

ISO8601TLDateFormat的輸出是

3912-03-17T00:00:00.000 + 0100

正如你可以看到,今年是1900年以上,或者其他任何未來以外的人都會需要。我已仔細研究了其全部旅程中的Date對象,並報告了它的日期是2012年,這正是我所期望的。爲什麼SimpleDateFormat分手?

+0

很可能出現了一個'Date'參與*地方*,因爲它的一年是1900年。 – 2012-03-17 15:13:31

+1

我不認爲這裏有足夠的信息...我們需要知道您對SimpleDateFormat所做的具體調用,以產生錯誤的輸出以及它如何被初始化等等。 – FrankieTheKneeMan 2012-03-17 15:17:06

+0

我已經得到了一個答案(下),但我會澄清我如何錯誤地構造我的Date對象。 – 2012-03-17 15:18:36

回答

4

問題是Date的構造函數沒有收到您的期望。從Java documentation摘自:

public Date(int year, 
      int month, 
      int date) 
Deprecated. As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date) or GregorianCalendar(year + 1900, month, date). 
Allocates a Date object and initializes it so that it represents midnight, local time, at the beginning of the day specified by the year, month, and date arguments. 
Parameters: 
year - the year minus 1900. 
month - the month between 0-11. 
date - the day of the month between 1-31. 

你需要記住,你構建一個日期0, 0, 1是1 1900年1月的

+0

謝謝 - 那麼,我假設'Date#getYear()'也爲您提供年份減去1900年? (這當然給我2012)。 – 2012-03-17 15:17:23

+0

http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Date.html#getYear()。只要閱讀文檔,你會發現你是對的。 – 2012-03-17 15:21:25

+0

介意如果我添加此鏈接:http://stackoverflow.com/questions/5621825/how-can-i-utilize-simpledateformat-with-calendar到您的答案? – 2012-03-17 15:27:47