3

I'm currently trying to determine the amount of time between two dates (one of which is the present date/time, the other an arbitrary future date). I'm using native Java and the Android API only, but I'm having a few problems with GregorianCalendar. My code so far can be seen below, but the problem I'm having is that the time between the two dates is massively inaccurate. As you'll be able to see I've set the future date as Christmas day in this example, but it's telling me there's over 62 days until then, which is clearly wrong.

    date = new GregorianCalendar();
    currentTime = date.getTimeInMillis();
    calendar = new GregorianCalendar();
    calendar.set(2011, 12, 25, 0, 0, 0);
    long difference = calendar.getTimeInMillis()-currentTime;

    long x = difference / 1000;
    seconds = x % 60;
    x /= 60;
    minutes = x % 60;
    x /= 60;
    hours = x % 24;
    x /= 24;
    days = x;

While debugging I added date.set(2011, 11, 23, 13, 1, 15); which was much more accurate, but it still displayed 32 days when I believe the correct amount of days is 31.

Thanks very much in advance for any help, much appreciated.

1

4 Answers 4

2

the problem in your code is the method calendar.set(2011, 12, 25, 0, 0, 0); what you want is calendar.set(2011, 11, 25, 0, 0, 0);

you can use Calendar.DECEMBER too.

The javadoc is clear for this method:

  • @param month the value used to set the MONTH calendar field. * Month value is 0-based. e.g., 0 for January.
1
  • FYI: The Joda-Time library has many advantages over the java.util.Date and .Calendar classes including knowing January is month 1 and December is month 12. Jun 12, 2014 at 5:14
2

java.time

The new java.time framework built into Java 8 and later supplants the old confusing java.util.Date/.Calendar classes

The Tutorial demonstrates how to get a span of time defined as a total number of days as well as a Period, a logical number of years and months and days.

LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(1960, Month.JANUARY, 1);

Period p = Period.between(birthday, today);
long p2 = ChronoUnit.DAYS.between(birthday, today);
System.out.println("You are " + p.getYears() + " years, " + p.getMonths() +
               " months, and " + p.getDays() +
               " days old. (" + p2 + " days total)");

The code produces output similar to the following:

You are 53 years, 4 months, and 29 days old. (19508 days total)

I would improve on the Tutorial’s example by passing a time zone to the now rather than relying implicitly on the JVM’s current default time zone which can change at any moment. While a LocalDate has no time zone assigned (that's what local means), in determining the date a time zone is crucial. For example, a new day dawns earlier in Paris than in Montréal.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( zoneId );

To get days until next birthday, construct a future date by substituting the year. The Java.time framework uses immutable objects, so this syntax shown creates a new object based on the values of the original while leaving the original intact and unaffected.

LocalDate birthdayThisYear = birthday.withYear( today.getYear() );
if ( birthdayThisYear.isBefore( today ) ) {
    birthdayThisYear.plusYears( 1 );
}
long daysUntilBirthday = ChronoUnit.DAYS.between( today , birthdayThisYear );

Joda-Time

The Joda-Time library provided the inspiration for java.time. Use Joda-Time when Java 8 technology is not available such as in Android. For Android specifically you may find special builds of Joda-Time from other sources to mediate some slow loading problem in Dalvik.

In this case the code is similar between Joda-Time and java.time.

DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
LocalDate today = LocalDate.now( zone );
LocalDate birthdate  = new LocalDate( 1966 , 1 , 2 );
LocalDate nextBirthday = birthdate.withYear( today.getYear() );
if ( nextBirthday.isBefore( today ) ) {
    nextBirthday = nextBirthday.plusYears( 1 );
}
int daysUntilBirthday = Days.daysBetween( today , nextBirthday ).getDays();

Joda-Time also offers a Period class. However this class handles partial days whereas java.time Period is whole days only. So we need to convert our LocalDate instances to DateTime instances to feed into the Period constructor.

DateTime start = today.toDateTimeAtStartOfDay( zone );
DateTime stop = nextBirthday.toDateTimeAtStartOfDay( zone );
Period period = new Period( start , stop );

The default formatter uses ISO 8601 standard formats. So calling period.toString() renders something like this for three months and two days:

P3M2D

2

First I suggest you use library methods for the calculations. For one thing, you should not reinvent the wheel. Second, some of the calculations may get tricky, for example if you also want to report months or years and need to take different month lengths and leap years into account. Not least, while it’s easy to divide by 60 for converting from seconds to minutes while writing the code, while reading it a method name that has ‘minutes’ or ‘seconds’ in it will more clearly convey why you are dividing by 60.

These days Java has two classes for amounts of time:

  • Duration is for time between clock times, for example 2 hours 46 minutes 30 seconds (it can handle days too, but knows neither weeks nor months).
  • Period is for time between dates, for example 2 months 9 days.

For a general solution I will show how you may use both for your task. I first find the Period between the dates. If that is from today at 2 PM to the day after tomorrow at 10 AM, you will get two days where we wanted 1 day 20 hours, so we need to adjust for that by subtracting 1 day before calculating the Duration.

    LocalDateTime dateTimeOne = LocalDateTime.of(2016, Month.APRIL, 25, 9, 5, 30);
    LocalDateTime dateTimeTwo = LocalDateTime.of(2017, Month.MAY, 15, 9, 10, 50);

    Period p = Period.between(dateTimeOne.toLocalDate(), dateTimeTwo.toLocalDate());
    LocalDateTime dtOnePlusPeriod = dateTimeOne.plus(p);
    if (dtOnePlusPeriod.isAfter(dateTimeTwo)) { // too far
        p = p.minusDays(1);
    }
    Duration d = Duration.between(dateTimeOne.plus(p), dateTimeTwo);

    long hours = d.toHours();
    d = d.minusHours(hours);
    long minutes = d.toMinutes();
    d = d.minusMinutes(minutes);
    long seconds = d.getSeconds();

    if (p.isZero() && d.isZero()) {
        System.out.println("0 seconds");
    } else {
        if (p.getYears() != 0) {
            System.out.print("" + p.getYears() + " years ");
        }
        if (p.getMonths() != 0) {
            System.out.print("" + p.getMonths() + " months ");
        }
        if (p.getDays() != 0) {
            System.out.print("" + p.getDays() + " days ");
        }
        if (hours != 0) {
            System.out.print("" + hours + " hours ");
        }
        if (minutes != 0) {
            System.out.print("" + minutes + " minutes ");
        }
        if (seconds != 0) {
            System.out.print("" + seconds + " seconds");
        }
        System.out.println();
    }

This prints

1 years 20 days 5 minutes 20 seconds

By using LocalDateTime I am ignoring changes to and from summer time (DST). If you need to take these into account, just use ZonedDateTime instead.

All the classes are in the java.time package. I will include a link to the Oracle tutorial at the bottom.

If you want to use java.time on Android, you get them in the ThreeTenABP. More links below.

With Java 9 will come some new methods in Duration, toHoursPart(), toMinutesPart() and toSecondsPart() that will give us the hours, minutes and seconds we want, much the way I have already done with Period. Then we will no longer need to subtract first the hours and then the minutes while calculating the indivivual fields.

Links

0

Instead of doing this :

 long x = difference / 1000;
seconds = x % 60;
x /= 60;
minutes = x % 60;
x /= 60;
hours = x % 24;
x /= 24;
days = x;

build a Date object with the difference between the two dates (long value). Then you can do a setDate(Date) on a Calendar object and parse it.

Alternatively, you can take a look at the Joda Time Api, which is relatively easy to use.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.