calculate between two dates in java code example
Example 1: 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));
System.out.println("Number of Days between dates: "+daysBetween);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Example 2: java 8 datediff in days
LocalDate dateBefore;
LocalDate dateAfter;
long daysBetween = DAYS.between(dateBefore, dateAfter);