java - Detect invalid date on Calendar.set() -
i have method returns me date() changed 1 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() unable give exception when field trying set not compatible date in question. so, in case:
date date = new date(); date = getdatechanged(date, calendar.day_of_month, 29); date = getdatechanged(date, calendar.month, 1); // feb
date is, in end, 01/03/15, because calendar.set() detects february can't set day 29, automatically set's date next possible day (i thinks how routine works).
this not bad, however, in case,
i want detect date i'm trying build impossible , then start decrementing day, in case i'm trying achieve 28/02/15, how can this?
example:
29/02/15 ===> 28/02/15
you can use cal.getactualmaximum(calendar.day_of_month)
find maximum days in given month calendar instance.
this way, can handle case mentioned above yourself.
also see answer here: number of days in particular month of particular year?
Comments
Post a Comment