I have a CalendarView that allows a user to select a date and enter activities.
I have a method that is called whenever the selected date is changed as follows:
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));
}
The method is being called everytime the date selected changes, the issue is the GregorianCalendar is not updating each time the method is called. Whenever I select a new day,
I/System.out: With gregorian calendar
I/System.out: Day: 5
I/System.out: Month: 2
I/System.out: Year: 1
is printed out and does not update when a new date is selected.
I can't figure out how to force the GregorianCalendar to update and the javadoc for CalendarView says that getDate() should return the currently selected date in milliseconds since unix epoch
As it turns out Calendar.DAY_OF_MONTH
, Calendar.MONTH
, and CALENDAR.YEAR
are not fields with that information, but integers representing which you are looking for when you call Calendar.get();
So fixing this was rather simple was I learned that, the proper code is:
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)));
}