Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two dates in String format? [duplicate]

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";
like image 708
Klausos Klausos Avatar asked Sep 01 '15 11:09

Klausos Klausos


1 Answers

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.

like image 76
Danil Gaponov Avatar answered Oct 02 '22 05:10

Danil Gaponov