I have to calculate the next date based on the current date. For example, say today is '05-NOV-2014' and user have gave an input like 1st Monday. so based on the user input if the 1st Monday of the current month has already gone past then i have to find out the 1st Monday of next month. if the 1st Monday is yet to come in the current month then i have to find out the date within the current month.
I am using java.util.Calendar class.
//user inputs
int dayOfWeek = 3; // as user has provided 'Tuesday'
int noOfWeek = 1; // as user provided 1st
Calendar cal = Calendar.getInstance(); // getting the current instance.
int currentDayOfWeek = Calendar.getInstance().get(Calendar.DAY_OF_WEEK); // getting the cCurrentDayOfWeek in integer.
int currentNoOfWeek = Calendar.getInstance().get(Calendar.DAY_OF_WEEK_IN_MONTH); // getting which week it is in the current month
if(noOfWeek < currentNoOfWeek){
// the date has gone past in the current month.
}
else if ((noOfWeek == currentNoOfWeek) && dayOfWeek < currentDayOfWeek){
// though the week number is same but as the currentDayOfWeek is greater than the provided day so in this case also date has gone past in the current month.
}
No able to proceed further. seeking your help.
Here's an idea. Continue to roll your Calendar instance one day [cal.add(DAY, 1)] per iteration (i.e., wrap in loop), each time checking that you are in the Day/Week specified as input. Finish and extract the date once such condition is met.
Also, substitute calls to Calendar.getInstance().get() for cal.get() after the "cal" variable declaration.
It was a pretty cool problem you have, and this is the solution I came up with and my approach:
First what you had:
Some things to note: I've put both the if and if-else into a single if, since in both cases you want to go to the next month, and also made it a separate method (making it a separate method is just a preference of myself, to keep things structured and organized).
Another thing I've noticed was an error in your if and else-if. It should be
noOfWeek < currentNoOfWeek
instead ofnoOfWeek > currentNoOfWeek
and((noOfWeek == currentNoOfWeek) && dayOfWeek > currentDayOfWeek)
instead of((noOfWeek == currentNoOfWeek) && dayOfWeek < currentDayOfWeek)
(the<
and>
are reversed).Now the calculateNextValidDate-method, which was where your problem lies. My approach is as follows:
This gave me the following code:
This code gave me the following output (on Wednesday 5th of November 2014 - with
3 [Tuesday]
and2
as input):Also note the
// TODO:
I've added in the main-method of the first code-part of this post. If the user-input is invalid (like a negative week or dayOfMonth for example), it can go through the while-loops too many times. I leave it up to you to validate the user-input.