I have 2 dates in a String format (ex. 2012-04-23, 2012-03-08), and I want to find the difference between them.
What is the best way to calculate that in Java?
I am just concerned with the date and not the time
I have 2 dates in a String format (ex. 2012-04-23, 2012-03-08), and I want to find the difference between them.
What is the best way to calculate that in Java?
I am just concerned with the date and not the time
You can convert string to date using:
String dateString = "2012-04-23";
Date date = new SimpleDateFormat("yyyy-mm-dd").parse(dateString);
You can read about SimpleDateFormat further here.
As to difference between two dates, you can calculate it in milliseconds with:
int milliseconds = dateOne.getTime() - dateTwo.getTime();
getTime()
returns the number of milliseconds since January 1, 1970.
To convert it in days, use:
int days = milliseconds / (1000 * 60 * 60 * 24)
If you are willing to add a third party jar to your project, then check the jodatime
DateTimeFormat
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
DateTime dt = formatter.parseDateTime(your-string);
interval
Interval interval = new Interval(time1, time2);
You also might want to check the difference between interval and duration which are concepts in jodatime lib
Use SimpleDateFormat to turn the strings into Date objects and use the getTime() method on Date to get the equivalent time in milliseconds. Take the difference between the two milliseconds values.
You may want to you DateFormat, Date and Calendar combination as below:
DateFormat dFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = dFormat.parse("2012-04-23");
Date date2 = dFormat.parse("2012-03-08");
long timeDifInMillis = date1.getTime() - date2.getTime();
Date dateDiff = new Date(timeDifInMillis);
Calendar diffCal = Calendar.getInstance();
diffCal.setTime(dateDiff);
System.out.println("Days="+diffCal.get(Calendar.DAY_OF_MONTH));
System.out.println("Months="+diffCal.get(Calendar.MONTH));
System.out.println("Years="+(diffCal.get(Calendar.YEAR)-1970));