0

First , there is a base date for comparsion

Date baseDate = dateFormat.parse("2013-01-01");

And there is a list of event date to compare with the base date e.g. Date date2 = dateFormat.parse("2013-01-02");

So, I would like to get the compare result (in day unit), in this case it is 1.

And if

Date date3 = dateFormat.parse("2012-12-31");

Then , the result should be -1

How can I achieve that? Tried baseDate .compareTo(date3) but it only return true/false. Thanks for helping

user782104
  • 13,233
  • 55
  • 172
  • 312
  • What kind of Date is it? java.util.Date? java.sql.Date? – Karakuri Aug 12 '14 at 03:11
  • java.util.Calendar; java.util.Date; thanks – user782104 Aug 12 '14 at 03:12
  • possible duplicate of [http://stackoverflow.com/questions/2517709/comparing-two-dates-to-see-if-they-are-in-the-same-day](http://stackoverflow.com/questions/2517709/comparing-two-dates-to-see-if-they-are-in-the-same-day) – bhargavg Aug 12 '14 at 03:13
  • I would like to get the difference in date unit instead of checking whether two day is the same day . Thanks for your remind – user782104 Aug 12 '14 at 03:14

3 Answers3

2

Another option is to call java.util.Date.getTime() in your Date objects, which returns the Date as a millisecond value. You can them calculate (date2.getTime() - baseDate.getTime()) / 24*60*60*1000.

Reference: https://developer.android.com/reference/java/util/Date.html#getTime()

Leandro
  • 949
  • 6
  • 8
  • it seems the 24*60*60*1000 can not convert to date, I check that now, thanks – user782104 Aug 12 '14 at 03:26
  • If you cast the above equation to `int`, you should have the number of days between the 2 dates. The positive or negative will represent if `date2` was after (positive) or before (negative) the `baseDate`. – Leandro Aug 12 '14 at 03:34
1
    String dateStart = "01/14/2014";
    String dateStop = "01/13/2014";

    Date d1 = null;
    Date d2 = null;
    SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");

    try {
        d1 = format.parse(dateStart);
        d2 = format.parse(dateStop);

        //in milliseconds
        long diff = d2.getTime() - d1.getTime();

        long diffDays = diff / (24 * 60 * 60 * 1000);

        System.out.print(diffDays + " days, ");
    }
    catch (Exception e){

    }
Aniruddha
  • 4,477
  • 2
  • 21
  • 39
0

java.util.Date has a compareTo() function that conforms to the Comparable interface. This method returns an integer.

Karakuri
  • 38,365
  • 12
  • 84
  • 104