calendar comparison is not working
i have written this code and its not working......
indate = "13/1/2011"
Calendar cd1 = Calendar.getInstance();
String[] StartDate = split(inDate.trim(),"/");
cd1.set(Calendar.DAY_OF_MONTH, Integer.parseInt(StartDate[0]));
cd1.set(Calendar.MONTH, Integer.parseInt(StartDate[1]));
cd1.set(Calendar.YEAR, Integer.parseInt(StartDate[2]));
currentDate ="14/1/2011"
String CurrentDate = com.connection.loginscreen.currentDate;
Calendar cd2 = Calendar.getInstance();
String[] resultc = split(CurrentDate.trim(), "/");
cd2.set(Calendar.YEAR, Integer.parseInt(resultc[2]));
cd2.set(Calendar.MONTH, Integer.parseInt(resultc[0]));
cd2.set(Calendar.DAY_OF_MONTH, Integer.parseInt(resultc[1]));
if (cd1.before(cd2))
{
check ="开发者_JAVA百科1";
}
it is not working.....
This is almost certainly not what you want:
cd1.set(Calendar.MONTH, Integer.parseInt(StartDate[1]));
Calendar.MONTH
is zero-based... whereas humans usually read/write months in a 1-based fashion.
Leaving the details aside though, you really shouldn't be writing parsing code yourself anyway, unless you have a particularly weird format which isn't handled by libraries. If you really want to stick with the Java libraries, use SimpleDateFormat
to parse it. Doing the parsing yourself will lead to mistakes like the one above and the one that jk pointed out. It's like building XML up by hand from strings: don't do it - use libraries.
Personally though, I'd recommend using Joda Time for all date/time work in Java. It's a much nicer API.
Don't do the parsing yourself. To convert a String to a Date, use a DateFormat, like this:
DateFormat f = new SimpleDateFormat("dd/M/yyyy");
String indate = "13/1/2011";
Date cd1 = f.parse(indate);
String currentDate ="1/14/2011";
DateFormat f2 = new SimpleDateFormat("M/dd/yyyy");
Date cd2 = f2.parse(currentDate);
if (cd1.before(cd2))
{
check ="1";
}
Check the SimpleDateFormat javadocs to see what patterns are defined and how it is used.
精彩评论