42

I know this isn't "the way it's supposed to work", but still: If you have two DateTime objects, what's a good way to subtract them? Convert them to Date objects?

DateTime start = new DateTime();
System.out.println(start + " - doing some stuff");

// do stuff

DateTime end = new DateTime();
Period diff = // end - start ???
System.out.println(end + " - doing some stuff took diff seconds");
Grzegorz Oledzki
  • 23,614
  • 16
  • 68
  • 106
ripper234
  • 222,824
  • 274
  • 634
  • 905
  • 1
    [This](http://stackoverflow.com/questions/3802893/number-of-days-between-two-dates-in-jodatime#) should help you. – karmanaut Apr 04 '13 at 15:08
  • @karmanaut - thanks, closing as dup. – ripper234 Apr 04 '13 at 15:09
  • 2
    @karmanaut That question doesn't really cover the same ground. It counts the number of *days* between two instants, not a general way to go from a start and end date to a period. – millimoose Apr 04 '13 at 15:11
  • 1
    See this: http://stackoverflow.com/questions/1555262/calculating-the-difference-between-two-java-date-instances – Parkash Kumar Apr 04 '13 at 15:11
  • @ParkashKumar Good catch, an `Interval` is probably better for this use. – millimoose Apr 04 '13 at 15:13
  • @millimoose, maybe OP wouldn't use .getDays() method to get days between two days. But you are right. [Here](http://joda-time.sourceforge.net/faq.html#datediff) is the official document for this. – karmanaut Apr 04 '13 at 15:16

5 Answers5

57

Period has a constructor that takes two ReadableInstant instances:

Period diff = new Period(start, end);

(ReadableInstant is an interface implemented by DateTime, as well as other classes.)

millimoose
  • 39,073
  • 9
  • 82
  • 134
22

From your example you seem to want the difference in seconds so this should help :

Seconds diff = Seconds.secondsBetween(start, end);
bowmore
  • 10,842
  • 1
  • 35
  • 43
7

Does this help? http://joda-time.sourceforge.net/key_period.html It shows the below example

DateTime start = new DateTime(2004, 12, 25, 0, 0, 0, 0);
DateTime end = new DateTime(2006, 1, 1, 0, 0, 0, 0);

// period of 1 year and 7 days
Period period = new Period(start, end);

// calc will equal end
DateTime calc = start.plus(period);

// able to calculate whole days between two dates easily
Days days = Days.daysBetween(start, end);
Rush
  • 486
  • 2
  • 11
3

Depends in which precision you want to get. You should check the org.joda.time package and check for the Helper classes such as Hours, Days, etc.

Caesar Ralf
  • 2,203
  • 1
  • 18
  • 36
1

I think you can create a Period using this constructor which takes two DateTime objects.

tehlexx
  • 2,821
  • 16
  • 29