ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software

[Part 7] Create your own Calendar (Date/Time) library from scratch using Java

Updated on March 8, 2017

Part 7 - Count and Display

In Part 6, we fixed a few issues and modified the getDay(), getMonth(), getYear(), and nextDate() methods. We also created the formatDate() and countDaysBetween() methods. The methods are returning the correct results with the exact format so far and we're no longer encountering the ArrayIndexOutOfBoundsException and some comparison issues.

In this part, we will continue where we left off. We still have two remaining counting methods to create and three identify methods. Here we will do the following:

  • A method to count the number of months between two dates
  • A method to count the number of years between two dates
  • Three individual methods to identify the days, months, or years between two dates

Method
Purpose
countDaysBetween()
Returns the number of days between two dates.
countMonthsBetween()
Returns the number of months between two dates.
countYearsBetween()
Returns the number of years between two dates.
Methods for counting.

We created the countDaysBetween() method in Part 6 so we will skip it in this part and move forward to the other methods.

    public int countMonthsBetween(String fromDate, String toDate){
        int monthCount = 0;
        int yearDiff = getYear(toDate) - getYear(fromDate);

        if (yearDiff > 0){
            monthCount = ((yearDiff - 1) * 12) + (12 - monthID(fromDate)) + monthID(toDate);
        }
        else {
            monthCount = monthID(toDate) - monthID(fromDate);
        }

        return monthCount;
    }

Counting the number of months between two dates

In order to count the number of months between two dates, we need to check if the two dates are on the same year.

Line 3
We initialized the int variable "yearDiff" with the value of the second year minus the first year. We then use the value of "yearDiff" or the difference between two years in the "if" statement.

Line 5
First, we check if the difference is greater than zero which means that the two dates are on different years (e.g. 2010 - 2014 = 4). Then we use the formula below:

monthCount = ((yearDiff - 1) * 12) + (12 - monthID(fromDate)) + monthID(toDate);

Line 8
If the difference between two years is not greater than zero or if the two dates are on the same year, we simply subtract the month ID (or the order of the month) of the first date from the month ID of the second date.

For example, [1] "01-JAN-2015" and [4] "22-APR-2015" = 4 - 1 = 3.

We can break the formula on Line 5 into different parts by following how they are grouped within a parenthesis and separated by the addition operator "+". You can see what I mean in the image below:

Formula for monthCount().
Formula for monthCount().

Trying out the method

In the image above, we used the dates "14-AUG-2010" and "21-FEB-2014" as example. We divided the formula into three and added the results together. The result was 42. Now, let's see if our countMonthsBetween() method returns the same result.

You may use the code below in "SampleClass" for this.

        System.out.println("Number of months between 14-AUG-2010 and 21-FEB-2014: " + myCalendar.countMonthsBetween("14-AUG-2010", "21-FEB-2014"));
Result using the countMonthsBetween() method.
Result using the countMonthsBetween() method.

Further explanation

Looks like we got the same result from the program and manual computing. In case you are wondering how we arrived to such formula, I will explain how. In the first part of the formula, we have ((yearDiff - 1) * 12). We subtract 1 from the difference of the two years to get the number of years that are not overlapped by the other month.

In the example "14-AUG-2010" and "21-FEB-2014", it's like moving from "14-AUG-2010" to:

[1] 14-AUG-2011 --> [2] 14-AUG-2012 --> [3] 14-AUG-2013

..and stopping there because if we move further to "14-AUG-2014", we'll be overlapping the end point which is "21-FEB-2014". So here we only moved 3 times then we multiply that number to 12 because there are 12 months in a year and we have 3 whole years that do not overlap. This results to 36.

In the second part of the formula, we have (12 - monthID(fromDate)). This is to calculate the remaining months after the last move (04-AUG-2013) before we reach the end of the year 2013. Since August is the 8th month, this becomes 12 - 8 and results to 4. 4 is the number of the remaining months before the date "04-AUG-2013" reaches the end of 2013 just before it starts the year 2014.

[1] September --> [2] October --> [3] November --> [4] December

In the third part of the formula, we have monthID(toDate). Since February is the 2nd month, the result is simply 2. We've already dragged the starting point ("04-AUG-2013") to the edge of the 2013 or December. From there, we must count the number of months we'll pass through to get to the end point ("21-FEB-2014").

[1] January --> [2] February

monthCount = ((yearDiff - 1) * 12) + (12 - monthID(fromDate)) + monthID(toDate);

= 36 + 4 + 2

= 42

If we add all the results we got, just like in the previous image, we'll still get 42.

Below are more sample tests:

        System.out.println("Number of months between 02-JAN-2009 and 29-JAN-2012: " + myCalendar.countMonthsBetween("02-JAN-2009", "29-JAN-2012"));
        System.out.println("Number of months between 04-SEP-2011 and 23-FEB-2012: " + myCalendar.countMonthsBetween("04-SEP-2011", "23-FEB-2012"));
        System.out.println("Number of months between 27-OCT-2013 and 05-NOV-2013: " + myCalendar.countMonthsBetween("27-OCT-2013", "05-NOV-2013"));
Results for countMonthsBetween().
Results for countMonthsBetween().

Counting the number of years between two dates

Counting the number of years between two dates does not require conditional statements or anything special. Unlike the days and months, the year does not loop back from the end to the beginning, it just continues to increment.

In the method below, we simply get the year of the two dates and find the difference between the two.

    public int countYearsBetween(String fromDate, String toDate){
        return getYear(toDate) - getYear(fromDate);
    }
        System.out.println("Number of years between 11-JAN-2009 and 03-SEP-2009: " + myCalendar.countYearsBetween("11-JAN-2009", "03-SEP-2009"));
        System.out.println("Number of years between 05-DEC-2012 and 27-OCT-2014: " + myCalendar.countYearsBetween("05-DEC-2012", "27-OCT-2014"));
Results for countYearsBetween().
Results for countYearsBetween().

Displaying the in-between

We can now use the methods countDaysBetween() from Part 6, countMonthsBetween(), and countYearsBetween() to well, count the days, months, and years between two dates. What if we want to display those values that are in-between two dates? Let's say we want to create a calendar view that only includes dates between "02-FEB-2015" and "13-DEC-2015". The first step towards accomplishing that is creating methods that will identify and return the actual days, months, and years between.

Below is a table of the three display methods that we will create.

Method
Purpose
daysBetween()
Returns the days between two dates.
monthsBetween()
Returns the months between two dates.
yearsBetween()
Returns the years between two dates.
Methods to return the in-betweens.

Count and Identify

I would sometimes use the word "display" instead of "identify" but do not get confused. The methods we're about to create will only identify and return the values between two dates and we will decide on what to do with the values returned. In this case, we want to display the values. I ran a few samples to test the methods and you can see the result in the image below. The purple arrows mean that there are more results that I did not include in the screenshot because it was too long.

Count and display.
Count and display.

Identifying the days between two dates

Just like the other methods we previously created, we can also use the methods we created to count the days, months, and years between two dates to identify the actual days, months, and years. In fact, this is the reason why I created those methods first.

In the code below, we used the value of the variable "daysCount" to determine how many times we will run the code inside the while loop. The value of "daysCount" is the value returned by the countDaysBetween() method we created previously.

Line 6
The condition checks if "daysCount" is greater than zero or if there's any more days between to loop into.

Line 7
The variable "currentDate" is initialized with the value of the "fromDate" or the start point but this changes inside the while loop. The "currentDate" is assigned the value of the "nextDate". This happens as many times as the loop.

Line 8
The getDay(currentDate) gets the day of the "currentDate" as it changes and adds it to the value of the "daysBetween" variable. The " | " can be replaced with anything or removed.

Line 9
The "daysCount" value decreases by 1 until it reaches zero and gets out of the while loop.

Line 11
The value of the "daysBetween" variable is returned.

    public String daysBetween(String fromDate, String toDate){
        int daysCount = countDaysBetween(fromDate, toDate);
        String currentDate = fromDate;
        String daysBetween = "";

        while (daysCount > 0){
            currentDate = nextDate(currentDate);
            daysBetween = daysBetween + getDay(currentDate) + " | ";
            daysCount --;
        }

        return daysBetween;
    }

Displaying the days between two dates

Now to test the new method. To display the days between two dates, you can use the code below in "SampleClass".

        System.out.println("\n* Count and Display *");

        System.out.println("\nNumber of days from 01-MAR-2015 to 11-MAR-2015: " + myCalendar.countDaysBetween("01-MAR-2015", "11-MAR-2015"));
        System.out.println("These days are " + myCalendar.daysBetween("01-MAR-2015", "11-MAR-2015"));

        System.out.println("\nNumber of days from 25-FEB-2015 to 02-MAR-2015: " + myCalendar.countDaysBetween("25-FEB-2015", "02-MAR-2015"));
        System.out.println("These days are " + myCalendar.daysBetween("25-FEB-2015", "02-MAR-2015"));

        System.out.println("\nNumber of days from 25-DEC-2014 to 02-JAN-2015: " + myCalendar.countDaysBetween("25-DEC-2014", "02-JAN-2015"));
        System.out.println("These days are " + myCalendar.daysBetween("25-DEC-2014", "02-JAN-2015"));
Results of the daysBetween() method.
Results of the daysBetween() method.

Identifying the months between two dates

The definition of the monthsBetween() method is pretty much the same as daysBetween()'s but instead of using nextDate() to move forward, we use nextMonth() since we only need the month. You may have noticed that we use the full date in the daysBetween() method and the nextDate() method. These also return a full date. This is to make sure that despite us needing only the days, it still follows the limits of every month.

For example, if it reaches January 31, the next day should be February 1, not January 32.

    public String monthsBetween(String fromDate, String toDate){
        int monthCount = countMonthsBetween(fromDate, toDate);
        String currentMonth = getMonth(fromDate);
        String monthsBetween = "";

        while (monthCount > 0){
            currentMonth = nextMonth(currentMonth);
            monthsBetween = monthsBetween + currentMonth + " | ";
            monthCount --;
        }

        return monthsBetween;
    }

Displaying the months between two dates

Use the sample code below to test the monthsBetween() method.


        System.out.println("\n* Count and Display *");

        System.out.println("\nNumber of months between 01-JAN-2015 and 17-MAR-2015: " + myCalendar.countMonthsBetween("01-JAN-2015", "17-MAR-2015"));
        System.out.println("These months are " + myCalendar.monthsBetween("01-JAN-2015", "17-MAR-2015"));

        System.out.println("\nNumber of months between 19-SEP-2014 and 03-APR-2015: " + myCalendar.countMonthsBetween("19-SEP-2014", "03-APR-2015"));
        System.out.println("These months are " + myCalendar.monthsBetween("19-SEP-2014", "03-APR-2015"));

        System.out.println("\nNumber of months between 27-OCT-2013 and 27-OCT-2014: " + myCalendar.countMonthsBetween("27-OCT-2013", "27-OCT-2014"));
        System.out.println("These months are " + myCalendar.monthsBetween("27-OCT-2013", "27-OCT-2014"));
Results of the monthsBetween() method.
Results of the monthsBetween() method.

Identifying the years between two dates

The definition of the yearsBetween() method is different from the other two but is more simple. The condition for the while loop is a comparison of the first year (start point) and the second year (end point). As long as they are not equal, the code inside the loop keeps running. Every time the loop runs, the value of the "currentYear" variable increases by 1 until the condition is met (two years become equal).

    public String yearsBetween(String fromDate, String toDate){
        int currentYear = getYear(fromDate);
        String yearsBetween = "";

        while(currentYear != getYear(toDate)){
            currentYear ++;
            yearsBetween = yearsBetween + currentYear + " | ";
        }

        return yearsBetween;
    }

Displaying the years between two dates

In the image after the code below, the first pair of dates results to zero so there is no output when you run the yearsBetween() method with those two dates.

        System.out.println("\n* Count and Display *");

        System.out.println("\nNumber of years between 17-JUL-2014 and 26-DEC-2014: " + myCalendar.countYearsBetween("17-JUL-2014", "26-DEC-2014"));
        System.out.println("These years are " + myCalendar.yearsBetween("17-JUL-2014", "26-DEC-2014"));

        System.out.println("\nNumber of years between 08-MAY-2014 and 11-MAR-2015: " + myCalendar.countYearsBetween("08-MAY-2014", "11-MAR-2015"));
        System.out.println("These years are " + myCalendar.yearsBetween("08-MAY-2014", "11-MAR-2015"));

        System.out.println("\nNumber of years between 01-JAN-2000 and 01-JAN-2015: " + myCalendar.countYearsBetween("01-JAN-2000", "01-JAN-2015"));
        System.out.println("These years are " + myCalendar.yearsBetween("01-JAN-2000", "01-JAN-2015"));
Results of the yearsBetween() method.
Results of the yearsBetween() method.

End of Part 7

We can now count the days, months, and years between two dates. We can also identify them and display them if we want to. However, the days don't seem to be accurate enough. We only get numbers and we want to know if these days fall on a Sunday, Monday, Tuesday, etc. The use of two dates can be useful but what if we want to enter just one date and add days, months, or years to that date?

In Part 8, we will create the methods for those. Most of the codes are already pushed to the repository on GitHub before they are discussed here.

Read Part 8

© 2015 Joann Mistica

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.