All those pupil who are tired of searching the web for subtracting two dates, here is a simple logic
first find the difference to millilseconds
divide milliseconds to date
1.convert milliseconds to seconds
2.seconds to minutes
3.minutes to24hours
4.divide difference in milliseconds with above multiple
public class DateSubtraction {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws ParseException {
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, 28);
secondDate.set(2009, 8, 18);
// 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);
System.out.println("Difference:"+diffInDays);
}catch(Exception ex)
{
ex.printStackTrace();
}
}
}
first find the difference to millilseconds
divide milliseconds to date
1.convert milliseconds to seconds
2.seconds to minutes
3.minutes to24hours
4.divide difference in milliseconds with above multiple
public class DateSubtraction {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws ParseException {
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, 28);
secondDate.set(2009, 8, 18);
// 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);
System.out.println("Difference:"+diffInDays);
}catch(Exception ex)
{
ex.printStackTrace();
}
}
}
No comments:
Post a Comment