try{
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String str1 = "12/10/2013";
Date date1 = formatter.parse(str1);
String str2 = "13/10/2013";
Date date2 = formatter.parse(str2);
if (date1.compareTo(date2)<0)
{
System.out.println("date2 is Greater than my date1");
}
}catch (ParseException e1){
e1.printStackTrace();
}
You can use following:
public static boolean CheckDates(String startDate, String endDate) {
SimpleDateFormat dfDate = new SimpleDateFormat("dd-MMM-yyyy");
boolean b = false;
try {
if (dfDate.parse(startDate).before(dfDate.parse(endDate))) {
b = true; // If start date is before end date.
} else if (dfDate.parse(startDate).equals(dfDate.parse(endDate))) {
b = true; // If two dates are equal.
} else {
b = false; // If start date is after the end date.
}
} catch (ParseException e) {
e.printStackTrace();
}
return b;
}
String pattern = "dd-MM-yyyy HH:mm:ss";
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
Date one = dateFormat.parse(Date1String);
Date two = dateFormat.parse(Date2String);
Now you have two Date
objects, you can compare them.
You can convert String to Date like this:
String str = "12/12/1912";
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = formatter.parse(str);
And back to String
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
System.out.println("Date is : " + formatter.format(date));
And Date has before and after methods and can be compared to each other.
By the way there is also a library called Joda, you can also check it out.
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