I have this method that returns me a Date() changed by one of it's "fields" (DAY, MONTH, YEAR).
public static Date getDateChanged(Date date, int field, int value) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(field, value);
return cal.getTime();
}
However, cal.set() is unable to give an exception when the field we are trying to set is not compatible with the date in question. So, in this case:
Date date = new Date();
date = getDateChanged(date, Calendar.DAY_OF_MONTH, 29);
date = getDateChanged(date, Calendar.MONTH, 1); // feb
date is, in the end, 01/03/15, because Calendar.set() detects that February can't be set with day 29, so automatically set's date to the next possible day (I thinks this is how the routine works).
This is not so bad, however, in my case,
I want to detect that the date I'm trying to build is impossible and then start decrementing the day, so in this case what I'm trying to achieve is 28/02/15, how can I do this?
Example:
29/02/15 ===> 28/02/15