Compare Date In JSP

Hi guys, can I know how to compare dates in JSP?

Date d1 = new Date();
Date d2 = new Date();
int num = d2.compareTo(d1);

num is the value 0 if d1 is equal to d2; a value less than 0 if d2 is before d1; and a value greater than 0 if d2 is after d1.

This is basic comparison.

I would advise you to do the basic Java tutorial on the Sun website.


Date date1, date2;

(set up the dates as you see fit)

if (date1.before(date2)){

if (date1.after(date2)){

if (date1.equals(date2)){

Just bear in mind that the comparisons are accurate to the millisecond, so before/after/equals can be a VERY fine distinction.

thanks guys =D

erm guys i got 1 more question.

I got 2 string dates. For Example

String date1 = “30-10-2003”;
String date2 = “30-12-2003”;

any ideas how do i get the days different?

I do hope I’m not doing your homework :wink:

String date1 = "30-10-2003";
String date2 = "30-12-2003";
SimpleDateFormat formatter = new SimpleDateFormat ("dd-MM-yyyy");
Date d1 = formatter.parse(date1);
Date d2 = formatter.parse(date2);
long millisDiff = d2.getTime() - d2.getTime();
double daysDiff = (double)millisDiff/(1000*60*60*24);

This code throws a ParseException which you will have to deal with.

hehe. Nope…it is part of my assigmment…Stuck with this. Thanks so much. I got to rush 3 programming assignments in 2 weeks.

ASP, JSP, JAVA+OpenGL. Stress

Second from last line should be

long millisDiff = d2.getTime() - d1.getTime();

But you spotted that right?

yap =D

Thanks alot