ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software

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

Updated on April 3, 2015

Part 3 - Month ID and Month name

After Part 1 and Part 2, we are now able to parse the day, month, and year in a given input. Also, we can check if a year is a leap year or not and get the number of days per month. The problem is our program is completely dependent on the input. We hard code the date we want to pass into our methods but how do we make our computer think, for example, that the next month after January is February and so forth?

In this part, we will discuss:

  • ArrayList
  • Data type parameters
  • Adding items to an array list using the add() method
  • Getting the position of an item in an array list using the indexOf() method
  • Getting an item in an array list by its index using the get() method

The body of "SampleClass" below shows the lines we've already discussed. The screenshot was originally posted in Part 1. The next methods to be discussed are the monthID() and monthName() methods.

Test for all methods.
Test for all methods. | Source

We'll be passing the value of our variable "firstDate" in the following methods:

Method
Purpose
monthID()
Returns the ID of a given month name.
monthName()
Returns the month name of a given ID.
Methods and their purpose.

Month ID

Let us first take a look at the method monthID().

		System.out.println("*** First Date: " + firstDate + " ***");
		System.out.println(myCalendar.getMonth(firstDate) + "'s month ID is " + myCalendar.monthID(firstDate) + ".");

In the code above, we passed the date "01-JAN-2016" as an argument for the method monthID(). This gave us the output "JAN's month ID is 1."

The result after running the program.
The result after running the program.

It's not common sense

Months always come in a specific and fixed order. The first month is always January then comes February, March, and so on until the last month which is December. After the last day of December, the month resets and goes back to the first one which is January and repeat.

Why do I have to tell you this? This is basic stuff, who doesn't know this? Well, I am sure you already know this. It is common knowledge to us but as I've mentioned in the earlier parts, the computer does not have the same common knowledge as we do and we have to give it instructions in a mathematical form so it can somehow "mimic" the way we make decisions based on our common knowledge.

The order of the months in a year is always:

 
 
 
 
 
 
 
 
 
 
 
 
 
Month
JAN
FEB
MAR
APR
MAY
JUN
JUL
AUG
SEP
OCT
NOV
DEC
ID
1
2
3
4
5
6
7
8
9
10
11
12
Month names and IDs.

Assigning an ID for each month

In the table above, we gave each month an ID following a specific order. The computer understands numbers more. It may not have the same common knowledge as we do but at least now it knows that April comes later than March because April's ID which is 4 is greater than March's ID which is 3.

Now we have to associate these IDs or numbers 1 to 12 with the months starting from January to December. In the code below, I used an ArrayList. I created the object named "arrayList" based on the "ArrayList" class so I can use its methods. I also added "<String>" in the instantiation of the ArrayList class so it will only allow objects of string data type to be added in the array list.

The monthID() method.
The monthID() method.
		ArrayList<String> arrayList = new ArrayList<String>();

Then I used the arrayList.add() method to add all twelve months in the correct order.

		arrayList.add("JAN");
		arrayList.add("FEB");
		arrayList.add("MAR");
		arrayList.add("APR");
		arrayList.add("MAY");
		arrayList.add("JUN");
		arrayList.add("JUL");
		arrayList.add("AUG");
		arrayList.add("SEP");
		arrayList.add("OCT");
		arrayList.add("NOV");
		arrayList.add("DEC");

Calling out the months

Now that we have an array list containing all twelve months, we need to get the corresponding ID for the month we'll be given. We will use an item's position in an array or index as its ID. Since we've added the items in the correct order, we will not have a problem in the order of their indices. We have been very familiar with arrays in the previous parts of this article that you may have taken the guess that "JAN" will have the index 0 since it is the first item in the array.

To avoid confusion, I added a "+ 1" in the return statement after getting the index of the month so it follows our table above where January's ID is 1, February's ID is 2, and so on.

		return arrayList.indexOf(getMonth(date)) + 1;

What this line does

  1. Passes the value of date to getMonth().
  2. Passes the month returned by the getMonth() method to indexOf().
  3. Adds 1 to the index returned by the indexOf() method.
  4. Returns the final value.

Let's test if our method works for every month in a year. I will assume that the body of your monthID() method looks like the code below:

MyCalendar

public class MyCalendar {
	
	public int monthID(String date){
		ArrayList<String> arrayList = new ArrayList<String>();
		arrayList.add("JAN");
		arrayList.add("FEB");
		arrayList.add("MAR");
		arrayList.add("APR");
		arrayList.add("MAY");
		arrayList.add("JUN");
		arrayList.add("JUL");
		arrayList.add("AUG");
		arrayList.add("SEP");
		arrayList.add("OCT");
		arrayList.add("NOV");
		arrayList.add("DEC");
		
		return arrayList.indexOf(getMonth(date)) + 1;
	}

}

We can use the code below to test if it returns the correct ID for every month.

SampleClass

public class SampleClass {
	
	public static void main(String[] args) {
		MyCalendar myCalendar = new MyCalendar();
	
		System.out.println("JAN's month ID is " + myCalendar.monthID("01-JAN-2016") + ".");
		System.out.println("FEB's month ID is " + myCalendar.monthID("26-FEB-1991") + ".");
		System.out.println("MAR's month ID is " + myCalendar.monthID("05-MAR-2015") + ".");
		System.out.println("APR's month ID is " + myCalendar.monthID("08-APR-1965") + ".");
		System.out.println("MAY's month ID is " + myCalendar.monthID("11-MAY-2005") + ".");
		System.out.println("JUN's month ID is " + myCalendar.monthID("06-JUN-2001") + ".");
		System.out.println("JUL's month ID is " + myCalendar.monthID("09-JUL-1998") + ".");
		System.out.println("AUG's month ID is " + myCalendar.monthID("14-AUG-2012") + ".");
		System.out.println("SEP's month ID is " + myCalendar.monthID("17-SEP-2009") + ".");
		System.out.println("OCT's month ID is " + myCalendar.monthID("27-OCT-1984") + ".");
		System.out.println("NOV's month ID is " + myCalendar.monthID("19-NOV-1990") + ".");
		System.out.println("DEC's month ID is " + myCalendar.monthID("04-DEC-2014") + ".");
		
	}
	
}

The output we got is now similar to the table we've created earlier.

The monthID() method returns the ID for every month.
The monthID() method returns the ID for every month.

Month name

After we've assigned an ID for each month, the computer can now tell us the ID of a given month but this is not yet complete. Since our initial problem is how we can write a program that tells us the next month after a given month, returning just the ID of a month is still pretty useless because this time, the user (human) will not understand what it means. The value that must be returned is the next month's name itself. Let's write a simple algorithm to achieve our goal.

Algorithm

  1. Get the month ID of a given month.
  2. Add 1 to the month ID.
  3. Get the name of the month associated to the number equivalent to ID + 1.

Example

  1. January's month ID is 1.
  2. 1 + 1 = 2.
  3. The month ID 2's month name is February.

Result

Therefore, the next month after January is February.

So now we need a method that accepts a month ID and returns its month name. This is where the monthName() method becomes necessary.

		System.out.println("The month ID " + myCalendar.monthID(firstDate) + "'s name is " + myCalendar.monthName(myCalendar.monthID(firstDate)) + ".");

I added the line of code above to the previous one. After running the program, it generated a new ouput "The month ID 1's name is JAN."

The result after running the program.
The result after running the program.

Getting the name of a month ID

The body of the monthID() and monthName() methods look similar except for the return type and the return statement. Both methods use an ArrayList and adds the twelve months. You may think this is repetitive and a waste of code because I've created two methods that pretty much have the same body. Actually, it is. Getting the next date can be done in a single method but I chose to break it down to the very specific task and created an individual method for each so it would be easier to explain.

As mentioned in the disclaimer in Part 1, we will begin polishing the code once the library is completed.

The monthName() method.
The monthName() method.

The monthName() method, when invoked, accepts the argument monthID which should be any number between 1 and 12. The method is also declared as string which means it will return a value of string data type. In the return statement, we wrote arrayList.get(monthID - 1). The get() method of the ArrayList can be considered as the opposite of the indexOf() method that we used in the monthID() method.

Method
Purpose
indexOf()
Accepts the actual value and returns its position in the array.
get()
Accepts the index and returns the value associated to it in the array.
Methods in the ArrayList class.

We passed the argument "monthID - 1" to the get() method. We subtract 1 from the "monthID" value because the index always starts with 0. If our method receives the monthID 2, it should return the month "FEB" because it is the second month but in the array, "FEB" is the second item added to the list and since the index starts with 0 as the first item, the second item's index is 1 and therefore, 0 is equivalent to "JAN", 1 is equivalent to "FEB" and 2 is equivalent to "MAR". We don't want that confusion.

If we get rid of the "- 1" in the return statement, the output will be confusing.

return arrayList.get(monthID);
return arrayList.get(monthID);

If we keep the "- 1" in the return statement, the output will be predictable and that's how we want it.

return arrayList.get(monthID - 1);
return arrayList.get(monthID - 1);

What happened here is we got the value 2, we subtract 1, and it resulted to the value 1 then we got the value associated to that number which is "FEB". This is what happens every time we invoke the method. The user can now input 2 and expect that the result will be "FEB" or 4 and expect that the result will be "APR" and that's exactly what the user should get. The computer now somehow looks like it has the same common knowledge as we do.

The monthName() method returns the name for every month ID.
The monthName() method returns the name for every month ID.

Getting the next month

We can get the next month by passing the month ID + 1 to the monthName() method. This way the month ID will increase by one getting the next month in the array.

Example

The line myCalendar.monthName(1 + 1); where the first number (1) is the monthID of "JAN" and the next number added (+ 1) means "the next month".

		System.out.println("The next month after JAN is " + myCalendar.monthName(1 + 1));
		System.out.println("The next month after FEB is " + myCalendar.monthName(2 + 1));
Result for hard coded month ID + 1.
Result for hard coded month ID + 1.

We can also get the next month without hard coding the month ID by using the monthID() together with the monthName().

		System.out.println("The next month after JAN is " + myCalendar.monthName(myCalendar.monthID(firstDate) + 1));
		System.out.println("The next month after FEB is " + myCalendar.monthName(myCalendar.monthID("26-FEB-1991") + 1));
Using monthID() inside monthName().
Using monthID() inside monthName().

I assume that you've written the code below for the MyCalendar class. This includes the monthID() and monthName() method.

MyCalendar

public class MyCalendar {
		
	public int monthID(String date){
		ArrayList<String> arrayList = new ArrayList<String>();
		arrayList.add("JAN");
		arrayList.add("FEB");
		arrayList.add("MAR");
		arrayList.add("APR");
		arrayList.add("MAY");
		arrayList.add("JUN");
		arrayList.add("JUL");
		arrayList.add("AUG");
		arrayList.add("SEP");
		arrayList.add("OCT");
		arrayList.add("NOV");
		arrayList.add("DEC");
		
		return arrayList.indexOf(getMonth(date)) + 1;
	}	

	public String monthName(int monthID){
		ArrayList<String> arrayList = new ArrayList<String>();
		arrayList.add("JAN");
		arrayList.add("FEB");
		arrayList.add("MAR");
		arrayList.add("APR");
		arrayList.add("MAY");
		arrayList.add("JUN");
		arrayList.add("JUL");
		arrayList.add("AUG");
		arrayList.add("SEP");
		arrayList.add("OCT");
		arrayList.add("NOV");
		arrayList.add("DEC");
		
		return arrayList.get(monthID - 1);
	}
	
}

SampleClass

You can use the code below for "SampleClass" to test if the code you've written works. Try playing around with the values and see if you get the expected results.

public class SampleClass {
	
	public static void main(String[] args) {
		MyCalendar myCalendar = new MyCalendar();

		System.out.println("The next month after JAN is " + myCalendar.monthName(1 + 1));
		System.out.println("The next month after FEB is " + myCalendar.monthName(2 + 1));
		System.out.println("The next month after MAR is " + myCalendar.monthName(3 + 1));
		System.out.println("The next month after APR is " + myCalendar.monthName(4 + 1));
		System.out.println("The next month after MAY is " + myCalendar.monthName(5 + 1));
		System.out.println("The next month after JUN is " + myCalendar.monthName(6 + 1));
		System.out.println("The next month after JUL is " + myCalendar.monthName(7 + 1));
		System.out.println("The next month after AUG is " + myCalendar.monthName(8 + 1));
		System.out.println("The next month after SEP is " + myCalendar.monthName(9 + 1));
		System.out.println("The next month after OCT is " + myCalendar.monthName(10 + 1));
		System.out.println("The next month after NOV is " + myCalendar.monthName(11 + 1));
		System.out.println("The next month after DEC is " + myCalendar.monthName(12 + 1));
	}

}
IndexOutOfBoundsException
IndexOutOfBoundsException

Oops, an exception!

Our method was able to return the next month for months starting from January to November but encountered an exception when it tried to get the next month for December. This is expected since we have not implemented a "reset" yet where the month will automatically go back to January once it reaches the last month of the year - December.

We will fix this in the next parts of this article. For now, I assume that you've written the code above and is getting the same output including the error.

Important note

The codes above simply serve as a summary of what we have discussed in Part 3. You have to make sure that the methods we have created in the previous parts is added into the "MyCalendar" class in case you encounter errors about some methods not existing in the class.

End of Part 3

We have added two new methods and given more "identity" to our dates including an ID and a name for each. We can get the ID of a given month and the other way around. We can also get the next month by adding 1 to the month ID but we are still manually adding 1 or putting the monthID to get the output we want.

In the next part, we are going to eliminate all these efforts.

Read Part 4

© 2014 Joann Mistica

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.