Java help comparing Calendar objects
I have developed a Calendar widget in Java (for BlackBerry development, specifically). A user can view all of the days in a current month开发者_如何学运维, as well as move forward/backward in months/years.
When I draw my calendar (in a table format), I want to change the color of any days that are X days in advance of the current date. I can currently check for this ONLY if the calendar shown on the screen is the same month as the current month:
if (calendarMonth == currentMonth) {
for (int i = 1; i <= (NUM_DAYS_IN_MONTH); i++) {
if (i > currentDay + Constants.CALENDAR_DAYS_IN_ADVANCE) {
System.out.println("VALID: " + i);
}
}
}
But I am having trouble coding a solution for when the calendar shown is a different month from the current month. For example, today is January 26th, so the January calendar will show all of the January days as a grey color. When the user changes the month to February, then the following days should be grey:
Constants.CALENDAR_DAYS_IN_ADVANCE = 14;
1/26/2011 - 2/9/2011
Any days past that range will be a black color. So basically, I am looking to write a function that will accept two java.util.Calendar objects (the active calendar shown and a calendar for the current date), and the function will return an array of dates in the range of CURRENT DATE - CALENDAR_DAYS_IN_ADVANCE.
I also need to keep in mind the following:
1) I cannot compare dates with the java.util.Calendar.add() or java.util.Calendar.subtract() functions, as java for BlackBerry is limited
2) This has to work across years, too, for example December 2010 - January 2011
Can anybody help with the logic?
Thanks!
Let's say, you have 2 Calendar
instances: nowCal
is pointing to the 00:00:00 of your start date, and maxOffsetCal
is pointing to 23:59:59 of your end date.
Following code will print desired dates:
public class Test {
private final static long MILLIS_IN_DAY = 86400 * 1000;
public static void main(String[] args) {
Calendar nowCal = new GregorianCalendar();
setTime(nowCal, 29, 1, 2011, 0, 0, 0);
Calendar maxOffsetCal = new GregorianCalendar();
setTime(maxOffsetCal, 2, 2, 2011, 23, 59, 59);
long now = nowCal.getTimeInMillis(), endTime = maxOffsetCal.getTimeInMillis();
for (; now < endTime; now += MILLIS_IN_DAY ) {
System.out.println(new Date(now));
}
}
private static void setTime(Calendar c, int dayOfMonth, int monthOfYear, int year,
int hourOfDay, int minute, int second) {
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
c.set(Calendar.MONTH, monthOfYear - 1);
c.set(Calendar.YEAR, year);
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
c.set(Calendar.SECOND, second);
c.set(Calendar.MILLISECOND, 0);
}
}
if (calendarMonth == currentMonth)
is wrong. Never use == to compare objects. Operator == compare references, so it is true only if you deal with the same object but not different equal objects. You should use method equals()
instead.
精彩评论