-1

Before this question is marked as a duplicate, it's not. I know this question, and I tried to use it's answer, to no avail so far.

I've got a date on which some event occurred, and I've got DateTime.now(). I now want to display the words "today" or "yesterday" if the date is today or yesterdays dates. If not (it's further in the past) the date should simply be printed. For this I want to know the difference in days between DateTime.now() and the DateTime at which the event occurred. So I tried this:

DateTime actionDate = overviewevent.getActionDate();
Log.wtf(TAG, actionDate.toString()); // Prints 2013-09-06T08:47:04.000+01:00
LocalDate localActionDate = actionDate.toLocalDate();
LocalDate localNow = DateTime.now().toLocalDate();
// First try
Log.wtf(TAG, Integer.toString(localActionDate.compareTo(localNow)));
// Second try
Log.wtf(TAG, Integer.toString(DateTimeComparator.getDateOnlyInstance().compare(actionDate, DateTime.now())));

Even though there are 10 days between now() and the actionDate, both of the things I try just print "1".

Does anybody know how I can see how many days the dates are apart?

Community
  • 1
  • 1
kramer65
  • 50,427
  • 120
  • 308
  • 488
  • 1
    What is `DateTime`? This class doesn't seem to be part of the Android API. Also, the `compareTo` method is used for comparison (less, more, same) rather than for difference such as number of days. That's why it prints `1`. – Daniel Gabriel Sep 16 '13 at 21:47
  • @DanielGabriel - Excuse me. DateTime is coming from org.joda.time.DateTime; – kramer65 Sep 16 '13 at 21:50
  • Ok, thanks. See if this helps: http://stackoverflow.com/questions/3802893/number-of-days-between-two-dates-in-joda-time – Daniel Gabriel Sep 16 '13 at 21:51

1 Answers1

1

I would say it is not printing 1 but -1.

The compare function just compares two dates, it does not compute a time difference. Check the Joda Time documentation for more information. Also, I suggest you to read about the more general Java interface Comparator which is a fundamental unit of the Java language.

I've never used Joda Time so far, but I read here that the solution to your problem might be

Days.daysBetween(actionDate.toDateMidnight(), DateTime.now().toDateMidnight()).getDays()
Community
  • 1
  • 1
ovmjm
  • 1,624
  • 12
  • 15
  • I just tried that, but surprisingly, this now gives me -12256 (even though there are really only 10 days between 2013-09-06 and today (2013-09-16). Any idea why this could be? – kramer65 Sep 16 '13 at 22:01
  • You say today is 2013-09-16 but is your device telling so ? What does `DateTime.now()` print ? This would explain the `1`, maybe.. – ovmjm Sep 16 '13 at 22:10
  • Awesome! That was the problem indeed! Thanks a lot! – kramer65 Sep 17 '13 at 08:02