What is the easiest way to compare two dates in String format? I would need to know if date1
comes after/before date2
.
String date1 = "2015-12-01";
String date2 = "2015-12-31";
What is the easiest way to compare two dates in String format? I would need to know if date1
comes after/before date2
.
String date1 = "2015-12-01";
String date2 = "2015-12-31";
For a more generic approach, you can convert them both to Date
objects of a defined format, and then use the appropriate methods:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = format.parse(date1);
Date date2 = format.parse(date2);
if (date1.compareTo(date2) <= 0) {
System.out.println("earlier");
}
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.parse(date1, new ParsePosition(0));
Date d2 = f.parse(date2, new ParsePosition(0));
And then compare dates:
d1.compareTo(d2);
The comparison will return negative value if d1
is before d2
and positive if d1
is after d2
.
With JodaTime, simply:
DateTime d1 = DateTime.parse(date1);
DateTime d2 = DateTime.parse(date2);
Assert.assertTrue(d1.isBefore(d2));
Assert.assertTrue(d2.isAfter(d1));
I would advise you to convert them to Date
objects.
String date1 = "2015-12-01";
String date2 = "2015-12-31";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(sdf.parse(date1).before(sdf.parse(date2)));
Comparing them like:
if(date2 .compareTo(date1) > 0){
System.out.println(" ---- ");
}
is not an ideal option (date1 and date2 are strings) as it loses the flexibility and can lead to its own share of problems.
You can simply convert your string to dates:
Date date1 = sdf.parse("2015-12-01");
Date date2 = sdf.parse("2010-01-01");
Then the comparison is done like: if(date1.after(date2)){ System.out.println("Date1 is after Date2"); }
if(date1.before(date2)){
System.out.println("Date1 is before Date2");
}
if(date1.equals(date2)){
System.out.println("Date1 is equal Date2");
}
If I remember correctly there's a ParseException
to handle
Yes you can compare this as follows:
Date date1 = new Date();
Date date2 = new Date();
if(date1.before(date2)){
// statement
}
if(date1.after(date2)){
// statement
}