我有一个CalendarView,允许用户选择日期并输入活动。
每当更改所选日期时,我都会调用一个方法:
private void selectedDateChanged(CalendarView view, int year, int month, int dayOfMonth){
//note: _Calendar is set to the view when activity loads hence the
//the reason for not using view.getDate();
Long timeSinceEpoch = _Calendar.getDate();
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTimeInMillis(timeSinceEpoch);
System.out.println(String.format("With gregorian calendar \n Day: %s \n Month: %s \n Year: %s",
calendar.DAY_OF_MONTH, calendar.MONTH, calendar.YEAR));
}
每次选择的日期发生变化时都会调用该方法,问题是每次调用该方法时GregorianCalendar都不会更新。每当我选择新的一天时,
I/System.out: With gregorian calendar
I/System.out: Day: 5
I/System.out: Month: 2
I/System.out: Year: 1
打印出,并且在选择新日期时不会更新。
我无法弄清楚如何强制GregorianCalendar更新,CalendarView的javadoc说getDate()应该返回当前选择的日期(以毫秒为单位),因为unix epoch
答案 0 :(得分:0)
System.out.println(String.format("With gregorian calendar \n Day: %s \n Month: %s \n Year: %s",
dayOfMonth, month, year));
答案 1 :(得分:0)
事实证明Calendar.DAY_OF_MONTH
,Calendar.MONTH
和CALENDAR.YEAR
不是包含该信息的字段,而是表示您在调用Calendar.get();
时要查找的内容的整数
所以解决这个问题非常简单,我了解到,正确的代码是:
private void selectedDateChanged(CalendarView view, int year, int month, int dayOfMonth){
//note: _Calendar is set to the view when activity loads hence the
//the reason for not using view.getDate();
Long timeSinceEpoch = _Calendar.getDate();
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTimeInMillis(timeSinceEpoch);
//Notice instead of calling cal.DAY_OF_MONTH directly
//I now call calendar.get(Calendar.DAY_OF_MONTH)
System.out.println(String.format("With gregorian calendar \n Day: %s \n Month: %s \n Year: %s",
calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.MONTH), calendar.get(Calendar.YEAR)));
}