Set Calendar To Next Thursday
I'm developing an app in Android which have a service that must be executed every Thursday and Sunday at 22:00 What I do need, is to set a Calendar to that day and time. However, I
Solution 1:
I've found the below solution simpler, a bit more portable as it doesn't involve much math. Once you set it to Thursday I believe you can use thesetTime()
method on the calendar object to set it to 22:00.
//dayOfWeekToSet is a constant from the Calendar class
//c is the calendar instance
public static void SetToNextDayOfWeek(int dayOfWeekToSet, Calendar c){
int currentDayOfWeek = c.get(Calendar.DAY_OF_WEEK);
//add 1 day to the current day until we get to the day we want
while(currentDayOfWeek != dayOfWeekToSet){
c.add(Calendar.DAY_OF_WEEK, 1);
currentDayOfWeek = c.get(Calendar.DAY_OF_WEEK);
}
}
//usage:
Calendar c = Calendar.getInstance();
System.out.println(c.getTime());
SetToNextDayOfWeek(Calendar.THURSDAY,c);
System.out.println(c.getTime());
Solution 2:
Not many maths, solved this, so clean:
int weekday = calendar.get(Calendar.DAY_OF_WEEK);
if (weekday!=Calendar.THURSDAY){//if we're not in thursday
//we calculate how many days till thursday
//days = The limit of the week (its saturday) minus the actual day of the week, plus how many days till desired day (5: sunday, mon, tue, wed, thur). Modulus of it.
int days = (Calendar.SATURDAY - weekday + 5) % 7;
calendar.add(Calendar.DAY_OF_YEAR, days);
}
//now we just set hour to 22.00 and done.
Credit to: http://www.coderanch.com/t/385117/java/java/date-Monday
I just adapted and explained the code.
Solution 3:
Try this?
c.add(c.DAY_OF_YEAR, -7);
or
c.add(c.DAY_OF_YEAR, +7);
Solution 4:
calendar.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY);
Post a Comment for "Set Calendar To Next Thursday"