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
If you are willing to add a third party jar to your project, then check the jodatime
DateTimeFormat
interval
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 can convert string to date using:
You can read about SimpleDateFormat further here.
As to difference between two dates, you can calculate it in milliseconds with:
getTime()
returns the number of milliseconds since January 1, 1970.To convert it in days, use:
You may want to you DateFormat, Date and Calendar combination as below:
Check SimpleDateFormat, it has a parse function.