How would I get the date of the next first Wednesday of the month using the java calendar class. For example:
Today(24/03/2012) the next first Wednesday will be 04/04/2012
On(05/04/2012) the next first Wednesday will be 02/05/2012
thanks.
解决方案
This works
set start date
move to next month
move to first day in month
add days until we get to a wednesday
Code
import static java.util.Calendar.*;
public static void main(String[] args) {
System.out.println(getNextMonthFirstWed(new Date(112, 3 - 1, 24)));
System.out.println(getNextMonthFirstWed(new Date(112, 4 - 1, 05)));
}
private static Date getNextMonthFirstWed(Date date) {
Calendar c = getInstance();
c.setTime(date);
c.add(MONTH, 1);
c.set(DAY_OF_MONTH, 1);
// search until wednesday
while (c.get(DAY_OF_WEEK) != WEDNESDAY) {
c.add(DAY_OF_MONTH, 1);
}
return c.getTime();
}