I am somewhat struggling with this.
I want to setup my Calendar to let's say: Third Monday in February 2012. And I didn't find any way of doing this using Java.
For example, if I wanted to set my calendar for Christmas 2011, I can do this easily, this way:
Calendar when = Calendar.getInstance();
when.set (Calendar.MONTH, Calendar.DECEMBER);
when.set (Calendar.DAY_OF_MONTH, 25)
when.set (Calendar.YEAR, 2011);
But I am lost as to how to set it up for let's say Memorial Day 2012, which is the last Monday of May. This is my code, but it's obviously wrong, because I simply can't assume that the last Monday of May will be in the 4th week of May that year:
Calendar when = Calendar.getInstance ();
when.set (Calendar.DAY_OF_WEEK,Calendar.MONDAY);
when.set (Calendar.MONTH, Calendar.MAY);
when.set (Calendar.WEEK_OF_MONTH, 4)
when.set (Calendar.YEAR, 2012);
Any suggestions as to how I can programatically find out, in which week of the month of May 2012 (in example above) is the last Monday? Assuming I can get that information, I should be able to get my code above to work.
I need something which would basically work for any other examples. Something which could give an exact day for the same scenarios. Examples:
Which date is:
- 3rd Thursday of May 2015
- 1st Monday of June 2050
- 4th Tuesday of December 2012
- 2nd Wednesday of July 2000
I really need this for my project and I am sure it's simple, but I am breaking my head on this without any real results to show for :) And also couldn't find anything on the net.
Added:
Ok, this is where I've got for the last Monday in a month:
when.set (GregorianCalendar.MONTH, GregorianCalendar.MAY);
when.set (GregorianCalendar.DAY_OF_WEEK, Calendar.MONDAY);
when.set (GregorianCalendar.DAY_OF_WEEK_IN_MONTH, -1);
when.set (Calendar.YEAR, 2012);
But I am not sure how would I go about doing for example seconds Monday in the same month, like this?
when.set (GregorianCalendar.DAY_OF_WEEK_IN_MONTH, 2);
Any suggestions?