August 5 2015

Java date difference in days

Java date difference in days

Convert the dates into milliseconds using the getTime() method and calculate the difference (subtract) between them.

long diffMs = date2.getTime() – date1.getTime();

diffMs will have the difference between dates in milliseconds. diffMs can be converted to days manually or using java.util.concurrent.TimeUnit

long diffDays = diffMs / (24 * 60 * 60 * 1000);

or

long diffDays = TimeUnit.DAYS.convert(diffMs, TimeUnit.MILLISECONDS))

Example


package com.answersz.dateutils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class DateDifferenceInDays {

public static void main(String[] args) {

System.out.println("Java date difference in days");

SimpleDateFormat myFormat = new SimpleDateFormat("dd-MM-yyyy");
String dt1 = " 04-08-2015";
String dt2 = "07-11-2015";

try {
Date date1 = myFormat.parse(dt1);
Date date2 = myFormat.parse(dt2);
long diff = date2.getTime() - date1.getTime();

long diffInDays1 = TimeUnit.DAYS.convert(diff,TimeUnit.MILLISECONDS);

System.out.println("TimeUnit - Difference in days : " + diffInDays1);

long diffInDays2 = diff / (24 * 60 * 60 * 1000);

System.out.println("Difference in days : " + diffInDays2);

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

}

}

Output


Java date difference in days
TimeUnit - Difference in days : 95
Difference in days : 95

 


Copyright © 2014. All rights reserved.

Posted August 5, 2015 by answersz in category Core Java

Leave a Comment

Your email address will not be published. Required fields are marked *

*