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?
In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value "greater than 0" if date1 is after date2 and it returns a value "less than 0" if date1 is before date2.
Explanation: Here we are using DateTimeFormatter object to parse the given dates from String type to LocalDate type. Then we are using isEqual(), isAfter() and isBefore() functions to compare the given dates. We can also use the compareTo() function of the LocalDate class to compare the Dates.
In this very case you can just compare strings date1. compareTo(date2) . EDIT: However, the proper way is to use SimpleDateFormat : DateFormat f = new SimpleDateFormat("yyyy-mm-dd"); Date d1 = f.
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.
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(); } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With