Skip to content
Advertisement

How to compare two string dates in Java?

I have two dates in String format like below –

String startDate = "2014/09/12 00:00";

String endDate = "2014/09/13 00:00";

I want to make sure startDate should be less than endDate. startDate should not be greater than endDate.

How can I compare these two dates and return boolean accordingly?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement