Android difference between Two Dates

How do I calculate difference in days between two dates?

Android difference between Two Dates

In the given example we will learn how to calculate difference between two dates in java in terms of Second/ Minutes / Hours / Days.

public int getDateDiffFromNow(String date){
		int days = 0;
		try{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
			long diff = new Date().getTime() - sdf.parse(date).getTime();
			long seconds = diff / 1000;
			long minutes = seconds / 60;
			long hours = minutes / 60;
			days = ((int) (long) hours / 24);
			Log.i(TAG, "Date "+date+" Difference From Now :"+ days + " days");
		}catch (Exception e){
			e.printStackTrace();
		}
		return days;
}

 

Call this function:

String old_date =  "2016-11-05";
getDateDiffFromNow(old_date)

 

Output:

Date 2016-11-05 Difference From Now : 732 days
Top