get number of days between two dates in java code example

Example 1: calculate number of years months and days between two dates in java

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		
Date birth = sdf.parse("2000-01-01");
Date now = new Date(System.currentTimeMillis());
		
Calendar c = Calendar.getInstance();
c.setTimeInMillis(now.getTime() - birth.getTime());
int y = c.get(Calendar.YEAR)-1970;
int m = c.get(Calendar.MONTH);
int d = c.get(Calendar.DAY_OF_MONTH)-1;

Example 2: java number of days between dates

LocalDate start = LocalDate.parse("2020-11-03");
LocalDate end = LocalDate.parse("2020-12-15");

long diff = DAYS.between(start, end);

Example 3: find difference in days between two dates java

String dateStart = "01/14/2015 08:29:58";
String dateStop = "01/15/2015 11:31:48";

//HH converts hour in 24 hours format (0-23), day calculation
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

Date d1 = null;
Date d2 = null;

d1 = format.parse(dateStart);
d2 = format.parse(dateStop);

//in milliseconds
long diff = d2.getTime() - d1.getTime();

long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);

System.out.print(diffDays + " days, ");
System.out.print(diffHours + " hours, ");
System.out.print(diffMinutes + " minutes, ");
System.out.print(diffSeconds + " seconds.");

Example 4: calculate days between two dates in java

import java.util.Date;
import java.text.SimpleDateFormat;
class Example{
   public static void main(String args[]){
	 SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
	 String dateBeforeString = "31 01 2014";
	 String dateAfterString = "02 02 2014";

	 try {
	       Date dateBefore = myFormat.parse(dateBeforeString);
	       Date dateAfter = myFormat.parse(dateAfterString);
	       long difference = dateAfter.getTime() - dateBefore.getTime();
	       float daysBetween = (difference / (1000*60*60*24));
               /* You can also convert the milliseconds to days using this method
                * float daysBetween = 
                *         TimeUnit.DAYS.convert(difference, TimeUnit.MILLISECONDS)
                */
	       System.out.println("Number of Days between dates: "+daysBetween);
	 } catch (Exception e) {
	       e.printStackTrace();
	 }
   }
}

Example 5: java get number of months between two dates

LocalDate currentDay = LocalDate.of(1955, Month.MAY, 19);
		LocalDate desiredDay = LocalDate.now();
		Period age = Period.between(currentDay, desiredDay);
		int years = age.getYears();
		int months = age.getMonths();

		int numberOfMonthsBetweenDates =  months+years*12;

Tags:

Java Example