旧应用程序的部分内容已弃用,我正在尝试重建它。基本上它是一个带月视图的日历。 这是我的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
一起使用。
答案 0 :(得分: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 :(得分: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);
答案 2 :(得分: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);
}
答案 3 :(得分:1)
寻找可信和/或官方来源的答案。
确定
主要来源:
https://docs.oracle.com/javase/7/docs/api/java/util/Date.html
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
}
答案 4 :(得分:0)
以下是从Date
转换为Calendar
的示例代码。
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);
}