Compare Date, Calendar or String date in Android

Droid By Me
1 min readAug 30, 2018

--

Hello Android Coders,

Today we will bring the code for date comparison for date object, calendar object or string date. For any two date comparison, you have to convert that date(string or calendar object) into date (object).

By Date Object:
Date class has its own methods for date comparison: compareTo

if (date1.compareTo(date2) > 0) {
Log.i("app", "Date1 is after Date2");
} else if (date1.compareTo(date2) < 0) {
Log.i("app", "Date1 is before Date2");
} else if (date1.compareTo(date2) == 0) {
Log.i("app", "Date1 is equal to Date2");
}

Date class has also methods before and after. Using these methods we can also compare two date:

if(date1.before(date2)){
Log.e("app", "Date1 is before Date2");
}

if(date1.after(date2)){
Log.e("app", "Date1 is after Date2");
}

By Calendar Object:

Date date1 = calendar1.getTime();
Date date2 = calendar2.getTime();

Then compare both date using compareTo, before(date) or after(date).

By String date:

For String date comparison, make sure both string has same format like yyyy-MM-dd or dd-MM-yyyy or any else. Then parse string date to date object as below:

try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
Date date1 = sdf.parse("2018-08-30");
Date date2 = sdf.parse("2018-08-28");

} catch (Exception e) {
e.printStackTrace();
}

Here 2018–08–30 and 2018–08–28 both has same format of yyyy-MM-dd and using this format, we parse both string. Then after parsing string to date objects, compare both dates as same using compareTo, after(date) or before(date).

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Droid By Me
Droid By Me

Written by Droid By Me

By profession and passion : Android Developer

No responses yet

Write a response