2017-03-25 107 views
7

我的舊應用程序的部分已棄用,我試圖重建它。基本上它是一個帶月視圖的日曆。 這是我的gridview的適配器的一部分:GridView的日曆視圖

public View getView(int position, View view, ViewGroup parent) { 
    Date date = getItem(position); 
    int day = date.getDate(); 
    int month = date.getMonth(); 
    int year = date.getYear(); 
} 

int day = date.getDate(); int month = date.getMonth(); int year = date.getYear(); 已被棄用。我正嘗試使用Calendar類而不是Date,但無法做到這一點。我知道,對於檢索一天,一個月或一年,我可以用這個:

Calendar calendar = Calendar.getInstance(); 
calendar.get(Calendar.DAY_OF_MONTH); 

,但我不知道怎麼這行轉換:

Date date = getItem(position); 

Calendar使用。

回答

1

這裏是你如何轉換Date對象到Calendar對象:

Calendar cal = Calendar.getInstance(); 
cal.setTime(date); 

然後(像你說的),你可以這樣做:

int day = cal.get(Calendar.DAY_OF_MONTH); 
int month = cal.get(Calendar.MONTH) 
int year = cal.get(Calendar.YEAR); 
+0

好的,謝謝,所以它不能做「本地」沒有使用Date對象只有日曆對象? –

+0

沒有問題。如果你不想使用Date,那麼你需要將你的適配器數據集更改爲Calendar,並使getItem()返回Calendar。 – 345

2

您可以使用此行代碼:

只需更換此線

Date date = getItem(position); 

這一行:

Calendar calendar = Calendar.getInstance(); 
Date date = calendar.getTime(); 

下面是一個完整的例子給你:

Calendar calendar = Calendar.getInstance(); 
Date date = calendar.getTime(); 
int day = calendar.get(Calendar.DAY_OF_MONTH); 
int month = calendar.get(Calendar.MONTH); 
int year = calendar.get(Calendar.YEAR); 
1

首先你會想引用日曆。一旦你做到了這一點,你可以說Date date = calendar.getTime

public View getView(int position, View view, ViewGroup parent) { 
    Calendar calendar = Calendar.getInstance(); 
    Date date = calendar.getTime(); 
    int day = calendar.get(Calendar.DAY_OF_MONTH); 
    int month = calendar.get(Calendar.MONTH)  
    int year = calendar.get(Calendar.YEAR); 
} 
1

尋找答案來自可信的和/或官方渠道繪製。

主要來源:

  1. https://docs.oracle.com/javase/7/docs/api/java/util/Date.html

  2. https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html

Date不會被棄用。只有一些方法。

所以,

public View getView(int position, View view, ViewGroup parent) { 

    Date date = getItem(position); 
    long ms = date.getTime();https://docs.oracle.com/javase/7/docs/api/java/util/Date.html#getTime() 
    Calendar calendar = Calendar.getInstance();//allowed 
    calendar.setTimeInMillis(ms);//allowed https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#setTimeInMillis(long) 
    //calendar.setTime(date); is also allowed https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#setTime(java.util.Date) 
    int day = calendar.get(Calendar.DAY_OF_MONTH);//allowed 
    int month = calendar.get(Calendar.MONTH);//allowed 
    int year = calendar.get(Calendar.YEAR);//allowed 
} 
0

下面是示例代碼轉換從DateCalendar

public View getView(int position, View view, ViewGroup parent) { 
    Date date = getItem(position); 
    // convert a Date object to a Calendar object 
    Calendar calendar = Calendar.getInstance(); 
    calendar.setTime(date); 

    int day = calendar.get(Calendar.DAY_OF_MONTH); 
    int month = calendar.get(Calendar.MONTH); 
    int year = calendar.get(Calendar.YEAR); 
}