1

I'm using jdk 1.7 and using the Calendar class to calculate the difference between 2 dates. I'm using the below code but it gives inconsistent results. Meaning sometimes it's correct but sometimes it's off by a day or something and there is no pattern to it.

public class Test {

    public static void main(String ar[]) {

        System.out.println(calculateDays());
    }

    private static long calculateDays() {
        long days_past_due;
           Calendar cal1 = Calendar.getInstance();
           Calendar cal2 = Calendar.getInstance();
           cal1.set(2013, 12, 1);
           cal2.set(2013, 12, 30);
           days_past_due = getDifference(cal1, cal2, TimeUnit.DAYS);
        return days_past_due;
    }

    public static long getDifference(Calendar b, Calendar a, TimeUnit units) 
    {

        return units.convert(b.getTimeInMillis() - a.getTimeInMillis(), TimeUnit.MILLISECONDS);
    }

Examples:

Example 1: cal1.set(2013, 12, 1);
           cal2.set(2013, 12, 1);
           Answer returned: 0 (Correct)
Example 2: cal1.set(2013, 12, 1);
           al2.set(2013, 12, 2);
           Answer returned: -1 (Correct)
Example 3: cal1.set(2013, 11, 30);
           cal2.set(2013, 12, 1);
           Answer returned: -2 (Incorrect)
Example 4: cal1.set(2013, 8, 31);
           cal2.set(2013, 8, 31);
           Answer returned: 0 (Correct)
Example 5: cal1.set(2013, 8, 31);
           cal2.set(2013, 9, 1);
           Answer returned: 0 (Incorrect)
Example 6: cal1.set(2013, 6, 30);
           cal2.set(2013, 6, 30);
           Answer returned: 0 (Correct)
Example 7: cal1.set(2013, 6, 30);
           cal2.set(2013, 7, 1);
           Answer returned: -2 (Incorrect)

What is that I'm doing incorrectly here?

rgettman
  • 176,041
  • 30
  • 275
  • 357
Akshay Salvi
  • 71
  • 1
  • 10
  • this might be obvious...but all of the incorrect calculations span across two different months. maybe thats the cause? – Solace Sep 27 '18 at 23:59
  • 1
    Month numbers are zero-based in `Calendar`. – rgettman Sep 28 '18 at 00:01
  • also why convert milliseconds to milliseconds? – Scary Wombat Sep 28 '18 at 00:02
  • 1
    Your way of calculating the difference also will not work correctly across transitions to and from summer time (DST). `Calendar` can do that if you know how, but it’s cumbersome. I wouldn’t bother. I would add [the ThreeTen backport library](https://www.threeten.org/threetenbp/) to my project and use [java.time, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and everything would be straightforward. – Ole V.V. Sep 28 '18 at 08:23
  • Possible duplicate of [Why is January month 0 in Java Calendar?](https://stackoverflow.com/questions/344380/why-is-january-month-0-in-java-calendar) – Ole V.V. Sep 28 '18 at 08:24
  • 1
    @ScaryWombat The code in the question is converting milliseconds to days since `units` is `DAYS` in the call to `getDifference`. It’s not the easiest nor the correct way, though. – Ole V.V. Sep 28 '18 at 08:27
  • thanks for your comments. @OleV.V. what would be the easier way to do it then? Using the same Calendar class – Akshay Salvi Sep 28 '18 at 17:24
  • There is no easier way using the `Calendar` class. At least not if it should also be a correct way. – Ole V.V. Sep 28 '18 at 20:34
  • What I meant with “It’s not the easiest …” was, to convert between two time units I find it a bit simpler to do `TimeUnit.MILLISECONDS.toDays(diffInMillis)`. It’s less general, of course, and worse, it still doesn’t handle summer time transitions correctly. – Ole V.V. Sep 29 '18 at 06:19

3 Answers3

2

tl;dr

You should be using LocalDate with sane counting, instead of the troublesome Calendar class.

ChronoUnit.DAYS.between(
    LocalDate.of( 2013 , 11 , 30 ) ,
    LocalDate.of( 2013 , 12 , 1 )
)

See this code run live at IdeOne.com.

1

Crazy counting

You seem to be unaware of the crazy counting used in the terrible Calendar class: 0-11 for months January-December.

So cal1.set(2013, 11, 30) to cal2.set(2013, 12, 1) means October 30 to November 1, which is indeed two days, accounting for October 31. You apparently thought of this incorrectly as November 30 to December 1, but no.

This is index-counting, zero-based. Unfortunately, index-counting shows up all too often with some programmers inappropriately using what made sense with primitive arrays or memory-jumping in systems programming or old-school C-style programming. In common business apps with modern languages, ordinal-counting usually makes more sense. For example, thinking of January as first month, month 1, and December as twelfth month, month 12.

java.time

Fortunately, we have the java.time classes now. There is no reason for you to ever use the awful mess that is the legacy date-time classes such as Date, Calendar, and SimpleDateFormat.

For your use with Java 7, see the ThreeTen-Backport project linked in the bullets at bottom below.

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone.

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

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

If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.

ZoneId z = ZoneId.systemDefault() ;  // Get JVM’s current default time zone.

Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.

LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ;  // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.

Or, better, use the Month enum objects pre-defined, one for each month of the year. Tip: Use these Month objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety.

LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;

ChronoUnit.DAYS

To count elapsed days, use the ChronoUnit enum.

long days = ChronoUnit.DAYS.between( start , stop ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
1

The Javadoc for Calendar#set(int,int,int) says (my emphasis)

Parameters:

year - the value used to set the YEAR calendar field.

month - the value used to set the MONTH calendar field. Month value is 0-based. e.g., 0 for January.

date - the value used to set the DAY_OF_MONTH calendar field.

If you re-examine your examples with this in mind, and remember that dates get "normalized" (i.e. if you specify the 13th month it becomes the first month of the following year), you'll find that all the calculated differences are actually correct.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
  • when I put the first date as (2014, 2 , 10) March 10th, 2014 and the second date as (2014, 2, 8) March 8th 2014, it gives me the result as 1. When in fact it should be 2. Why did that happen? – Akshay Salvi Sep 28 '18 at 18:26
0

what would be the easier way to do it then? Using the same Calendar class

There is no easier way using Calendar. There is a more cumbersome ad error-prone way.

First you need to initialize your two Calendar objects correctly:

    Calendar cal1 = Calendar.getInstance();
    Calendar cal2 = Calendar.getInstance();
    cal1.clear();
    cal2.clear();
    cal1.set(2013, Calendar.NOVEMBER, 30);
    cal2.set(2013, Calendar.DECEMBER, 1);

A Calendar object despite its name represents a date, a time of day, a time zone and a calendar system. When we want to use it for a date in the Gregorian calendar in a time zone alone, we need to clear the fields first to get rid of the time of day, or it will interfere with the calculations to follow. Next use the named constants of the Calendar class for the months of the dates you wish to set to reduce confusion.

Second, to have Calendar take transitions to and from summer time (DST) and other anomalies into account there is no other way than adding the days and seeing when we are there — it’s the backward way of doing it:

    if (cal1.before(cal2)) {
        int daysPastDue = 0;
        while (! cal1.after(cal2)) {
            daysPastDue++;
            cal1.add(Calendar.DATE, 1);
        }
        // Now cal1 is after cal2, so we’ve counted 1 day too many. Compensate:
        daysPastDue--;
        System.out.println("Answer returned: " + daysPastDue);
    }

This prints:

Answer returned: 1

I certainly don’t encourage doing it the way I have shown. It’s relatively many lines of code, and it’s fairly easy to forget one detail and get a wrong result or make an off-by-one error. Upgrade to Java 8 or 9 or 10 or 11 if you can. If you cannot, Basil Bourque’s answer works nicely with the ThreeTen Backport library too, see his bullet about Java SE 6 and Java SE 7.

PS: While the TimeUnit enum is great for conversions between anything from microseconds to hours, don’t use it for days, at least not in this case. TimeUnit.DAYS counts 24 hours, while days in the calendar may be 23, 24 or 25 hours and occasionally have yet other lengths.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161