Reputation: 20565
I have a datepicker where the user selects a date and then a checkbox on what type of period he wants to get the date from. For example:
User selects the 1. of November and selects the checkbox "Month" in this case the end date will be increased by 1 and even if this sound simple enough its slowly starting to annoy me alot!
The problem is that Java doesnt have a great date object that works for this kind of thing so i thought that i would use Calendar but it isnt easy to increment a calendar date take for instance the following example:
endDate.set(startDate.YEAR, startDate.MONTH+1, startDate.DATE);
in theory this would increment the month by one being one larger than the start date. This works in about 90 % of the months EXECPT from December if you increase the month by 1 in December then the integer month return 13 same thing happens for startDate.DATE;
and startDate.Year;
My question is isnt there an easier way to do this? i could make a ton of If sentences but i really think that it is kinda redundant.
Upvotes: 0
Views: 117
Reputation: 272407
The standard recomendation here is to look at Joda-Time (see here for more info). It's a much more consistent/capable API with none of the threading issues that plague the standard Java date/formatting APIs and as such is widely used and accepted.
In terms of what you want above, I would suggest something like:
LocalDate d = ...
LocalDate nd = d.plusMonths(1);
The above will correctly handle month/year rollovers.
Upvotes: 1
Reputation: 24406
Use add
method of java.util.Calendar
.
endDate.set(startDate.YEAR, startDate.MONTH, startDate.DATE);
if(some_condition) {
endDate.add(Calendar.MONTH, 1);
}
Upvotes: 2
Reputation: 9974
You can use Calendar.add()
to add values to the calendar value, e.g. Calendar.add(Calendar.MONTH, 1)
this adds one month and takes into account that January is after December.
Upvotes: 1