Search code examples
javadatetimedatejodatimeduration

Get Time till Christmas using Joda Time


I need to calculate the time till Christmas in milliseconds. I'm using joda time and I tried using Period, but after wasting a lot of time on Google, I realized that this is wrong, and I could calculate milliseconds. However, my implementation is incorrect and I'm getting wrong results.

My code:

DateTime start = new DateTime(DateTime.now());
DateTime end = new DateTime(2012, 12, 25, 0, 0, 0 ,0);
org.joda.time.Duration duration = new Period(end, start).toDurationFrom(new Instant());
int millis = (int) DateTimeUtils.getDurationMillis(duration);
Log.d("Millis", String.valueOf(millis));

I tried looking at the Joda Time Documentation, but I could not find an answer.


Solution

  • To just calculate milliseconds, it's easy - no need to go via a Period at all.

    long milliseconds = end.getMillis() - start.getMillis();
    

    (It's not clear why you're calling new DateTime(DateTime.now()) by the way - just DateTime.now() will suffice.)

    EDIT: It works fine for me:

    import org.joda.time.*;
    
    public class Test {
        public static void main(String[] args) {
            DateTime start = DateTime.now();
            DateTime end = new DateTime(2012, 12, 25, 0, 0, 0, 0);
            System.out.println(end.getMillis() - start.getMillis());
        }
    }