0

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

Ghadeer
  • 608
  • 2
  • 7
  • 21

5 Answers5

3

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)
Edward Ruchevits
  • 6,411
  • 12
  • 51
  • 86
  • @EdwardRuchevits and what about diff in weeks/years/month? Your technic is not good for that since you dont know how many days in month 29/30/31. – Maxim Shoustin Dec 05 '12 at 22:40
  • Weeks? Divide `days` by **7**. Years? Divide `days` by **365.242**. Isn't it obvious? About months, well, it wil be more complicated. – Edward Ruchevits Dec 05 '12 at 22:46
  • The days between logic can fail on a day light savings boundary, because one day is 23 or 25 hours – Steve Kuo Dec 06 '12 at 00:04
2

If you are willing to add a third party jar to your project, then check the jodatime

DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");

DateTime dt = formatter.parseDateTime(your-string);

  • Find the difference between them -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

Community
  • 1
  • 1
mtk
  • 13,221
  • 16
  • 72
  • 112
1

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.

Chris Gerken
  • 16,221
  • 6
  • 44
  • 59
0

Check SimpleDateFormat, it has a parse function.

Cool
  • 11
  • 2
0

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));
Yogendra Singh
  • 33,927
  • 6
  • 63
  • 73