There are times when we need to calculate the difference between two dates.
For example:
There was requirement in a project on ticket reservation system to restrict the reservation of ticket to employees who have been hired for at least 6 months. In such cases we need to calculate the difference between two dates..
Below is an example code in java to calculate the difference between two dates:
import java.util.Calendar; public class DateDiffExample { public static void main(String[] args) { long diffInMillisec=0; long diffInDays=0; Calendar firstDate =null; Calendar secondDate =null; try{ // Create two calendars instances firstDate = Calendar.getInstance(); secondDate = Calendar.getInstance(); //Set the dates firstDate.set(2009, 8, 1); secondDate.set(2009, 7, 31); // Get the difference between two dates in milliseconds diffInMillisec = firstDate.getTimeInMillis() - secondDate.getTimeInMillis(); // Get difference between two dates in days diffInDays = diffInMillisec / (24 * 60 * 60 * 1000); }catch(Exception ex) { ex.printStackTrace(); } } }