Handout
Globsyn Skills
Globsyn Crystals, XI 11 and 12, Block EP, Sector V, Salt Lake Electronics Complex, Kolkata
700 091, India
All information, including graphical representations, etc provided in this presentation is for exclusive use of current
Globsyn Skills students and faculty. No part of the document may be reproduced in any form or by any means, electronic or
otherwise, without written permission of the owner.
DATE COMPARISON IN JAVA
To compare dates in Java you have two choices:
1. Create java.util.Date objects based on the dates that you'd like to compare.
use "public long getTime()" method of each date object to obtain number of
milliseconds since January 1, 1970, 00:00:00 GMT for each date, and
compare these long values using operators <, >, ==, <>, != as you see
fit.
2. Obtain two instances of the java.util.Calendar class through a call to one of
the "public static synchronized Calendar getInstance(...)" methods of the
Calendar instance. Set the date of each Calendar instance using one of its
"public final void set(...)" methods.
Then use Calendar methods:
"public abstract boolean equals(Object obj)",
"public abstract boolean after(Object when)",
"public abstract boolean before(Object when)"
to do the comparison, The following code uses the latter:
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
int year = 1999;
int month = 11;
int day1 = 10;
int day2 = 11;
cal1.set(year,month,day1);
cal2.set(year,month,day2);
String date1 = ""+year+"//"+month+"//"+day1;
String date2 = ""+year+"//"+month+"//"+day2;
if( cal2.equals(cal1) )
System.out.println(date1+" is the same as " + date2);
if( cal2.after(cal1) )
System.out.println(date2 + "is after "+date1);
else
System.out.println(date2 + "is before "+date1);
Page: 2 of 2
Version 1.00