Search code examples
androiddatetimejodatimeandroid-jodatime

Trying to find time difference in Joda Time between 2 DateTime objects


I'm trying to find the difference between 2 times using Joda Time. I've tried using some of the examples on here and can not get a value to return. Here is what I've tried: Where time is in a format like 17:23 and the to and from variables are time zones like America/Los_Angeles or Europe/London

    DateTime dtFrom = DateTime.now()
    DateTime dtTo = new DateTime(dtFrom.withZone(DateTimeZone.forID(to)));
    //calculate time difference
    Period period = new Period(dtTo, dtFrom) ;
    Minutes minutes = Minutes.minutesBetween(dtFrom, dtTo);
    long diffInMillis = dtFrom.getMillis() - dtTo.getMillis();

I've tried using different methods to compare these two and always get no value returned...period returns PT0S, minutes returns PT0M, and diffInMillis returns 0. What am I doing wrong here? Thanks!


Solution

  • You are using the method withZone() which is defined to preserve the (POSIX) instant in milliseconds since 1970-01-01T00:00Z. So dtFrom and dtTo have still the same instant meaning they describe the same global time although their local time representations are different due to different time zones.

    Result: The difference between two same instants is exactly equal to zero regardless which time unit you use.

    However, if you are interested into the local time difference instead please determine the zone offset difference, for example using the method getOffset().