How to compare two string dates in Java?
Here is a fully working demo. For date formatting, refer - http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Dating {
public static void main(String[] args) {
String startDate = "2014/09/12 00:00";
String endDate = "2014/09/13 00:00";
try {
Date start = new SimpleDateFormat("yyyy/MM/dd HH:mm", Locale.ENGLISH)
.parse(startDate);
Date end = new SimpleDateFormat("yyyy/MM/dd HH:mm", Locale.ENGLISH)
.parse(endDate);
System.out.println(start);
System.out.println(end);
if (start.compareTo(end) > 0) {
System.out.println("start is after end");
} else if (start.compareTo(end) < 0) {
System.out.println("start is before end");
} else if (start.compareTo(end) == 0) {
System.out.println("start is equal to end");
} else {
System.out.println("Something weird happened...");
}
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Convert them to an actual Date
object, then call before
.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd h:m");
System.out.println(sdf.parse(startDate).before(sdf.parse(endDate)));
Recall that parse
will throw a ParseException
, so you should either catch it in this code block, or declare it to be thrown as part of your method signature.