ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software

Create your own Calendar (Date/Time) library from scratch using Java

Updated on March 30, 2015
Joann Mistica profile image

Joann has been working as a software engineer for four years. She graduated with Bachelor of Science in Information Technology.

Part 1 - Getting the values we need

As we go along the journey of creating our own calendar library, we will learn a few things that will be necessary for each part. In this part, we will discuss:

  • Instantiating another class to have access to its methods
  • Access modifiers, public and private methods
  • Return types and special types
  • Difference between parameters and arguments
  • Parsing strings and integers
  • Delimiters
  • Arrays
  • Exporting and adding JAR files
  • Implementing methods from an imported library

Why should you create your own library?

There are plenty of existing Java libraries out there for different purposes. Most are already included as core libraries while others are open-source projects that can be downloaded online. Having all these resources available for free makes it pointless and time-consuming to create your own library if you simply want to get things done quickly.


Why should you make one anyway?

There are plenty of people who struggle in learning Java and the whole object-oriented programming concept. You can write code that runs perfectly without errors and get a correct output. The thing is, in every class you create, you are using methods in the core libraries. You pass an argument to a method and you get an output. Have you ever been curious how that happens? What happens behind the scenes? How does this line of code accept a value and return a specific output? How can it accept different values and through that, generate a different, but still relevant output? What kind of sorcery is this?

This article is for people who are curious, people who don't want to simply make things work but also want to get an idea of how things work.


Disclaimer

I'm simply one of the many humble admirers of the Java programming language. It took time for me to appreciate it until I realized how powerful it can be. In this article, I will show you how I got it done. There could be better ways to do it. Feel free to point anything out and feel free to do things your own way. Despite this article's purpose to show you how to create your own library, I will also discuss a few other things we will need as we advance to every line of code.

The first few steps will be simple and unpolished, just enough to show you how it works. In the beginning, we will use the long but simplest way to write our library. All methods and variables will be public and non-static. We will proceed to fixing any problems we may encounter and improve the code as we go.

Test for all methods.
Test for all methods.

I wrote a few lines of code in the main method of "SampleClass" to display the values returned by each method from the library I made. This is to verify if each method works and produces an expected output.

You can create the "MyCalendar" class side by side with the "SampleClass" in the same project and package first so you wouldn't have to keep exporting and importing the library.

public class SampleClass {
	
	public static void main(String[] args) {
		MyCalendar myCalendar = new MyCalendar();
		String firstDate = "01-JAN-2016";
	}
}

In the code above is the string variable "firstDate". This variable will be passed into the methods and the results will be displayed. We will go through each line, modify the values of "firstDate" and see how the output changes for each method. I will show the code behind these methods as well. We will create these methods one by one and test whether they return relevant results on different inputs.

The format for the variable “firstDate” is “DD-MON-YYYY”. We will enhance the code to accept different formats later on but for now, this will be the only format we will use for the dates we will input.

MyCalendar myCalendar = new MyCalendar();

In the line of code above, we instantiate or create an object of the “MyCalendar” class so we can use its methods.

Here, we chose the name “myCalendar” for our object. Now, we can use its methods by entering “myCalendar.<method>”. A Ctrl + Space after the period will show a list of methods available in the “MyCalendar” class.

MyCalendar methods.
MyCalendar methods.
System.out.println("*** First Date: " + firstDate + " ***");
System.out.println("Day: " + myCalendar.getDay(firstDate));
System.out.println("Month: " + myCalendar.getMonth(firstDate));
System.out.println("Year: " + myCalendar.getYear(firstDate));

In the code above, we display the value of the variable “firstDate”. In the next three lines, we pass the variable “firstDate” to the following methods:

Method
Purpose
getDay()
Get the day in the given date.
getMonth()
Get the month in the given date.
getYear()
Get the year in the given date.
Methods and their purpose.
The result after running the program.
The result after running the program.

Now let’s check the source code for the “MyCalendar” class to see how it generated the results above.

Method declaration in the MyCalendar class.
Method declaration in the MyCalendar class.

Access modifiers and return types

Let’s experiment with the getDay() method first. We start off by using the access modifier “public”* which means it can be accessed outside of its class. Since we’ll be using “MyCalendar” as a library, its methods must be accessible to other classes that will use it.

Next, we use the return type “int” since the method is expected to return an integer (Example: day 2). Following the type is the method name, we chose “getDay” for this one followed by a pair of parentheses. Inside the parentheses is a parameter or the variable in the method declaration named “date” with a string data type. This means that the argument or the variable that will be passed to the method when it is invoked should be of type string; otherwise an error will occur.

Since the variable "firstDate" is declared as a string in "SampleClass", the statement "myCalendar.getDay(firstDate)" did not generate an error.

The difference between a parameter and an argument

While both can be variables, people are often confused when a variable is called a parameter or an argument. Using the getDay() method as an example, I will show you the difference between the two and how to identify them.

	/* MyCalendar.java
	 * The "date" below is a parameter since it can be found
	 * in the method declaration.*/
	public int getDay(String date){
		String[] splitDate = date.split("-");
		
		return Integer.parseInt(splitDate[0]);
	}
		/* SampleClass.java
		 * The "firstDate" below is an argument since it is the variable
		 * passed to the method.
		 */
		System.out.println("Day: " + myCalendar.getDay(firstDate));

A few notes you're free to ignore

  • If the access modifier of the getDay() method was set to "private", it will not appear in the list of methods after Ctrl + Space. Any previous invocation of the method before the access modifier was changed will return an error "method is not visible".
  • For methods that don’t return a value, the type “void” should be used. Putting a return statement inside a method of type void will trigger an error. Declaring methods with any type aside from void will automatically require you to put a return statement.

Ctrl + Space.
Ctrl + Space.
Error.
Error.

Writing a method

When creating a method that returns a value, you must first figure out:

  • What is the purpose of this method?
  • How will the parameter, if any, help fulfill this purpose?
  • How will it be able to return the correct value regardless of the argument passed when the method is invoked?

The three questions above are questions I ask myself before creating public and non-static methods. You can make your own pointers or follow those three. Let's answer the questions above.


What is the purpose of this method?

What is this method supposed to do? We want the getDay() method to accept the argument "date" when it is invoked and get the value of "day".


How will a parameter, if any, help fulfill this purpose?

The parameter “date” is important since this will be the basis of the value that will be returned. The value of “day” is part of the “date”. (e.g. Date: 01-MAR-2014; Day: 01)


How will it be able to return the correct value regardless of the argument passed when the method is invoked?

In order for the method to return the correct “day” value, the value of “date” must be manipulated in some way. This means that simply returning whatever argument is passed into the method will not return the value for “day”, instead it will return the unchanged value of “date”.

Now that we know what we want to do with the method. Let's explain the body of the getDay() method.

	public int getDay(String date){
		String[] splitDate = date.split("-");
		
		return Integer.parseInt(splitDate[0]);
	}

Given that the value of "date" is "01-JAN-2016" and we only need the value "01", we write a code that will parse the value of "date" and leave us the value "01". First, we declare a string array variable called "splitDate" and its purpose is to split the date into three portions. Note our date format "DD-MON-YYYY" or day-month-year. To do that, we initialize the "splitDate" variable with the value "date.split("-")".

The split() method splits the value of our string variable "date". To find out where it should split the value, it needs a delimiter. Here, we use "-" as a delimiter.

 
 
 
 
 
 
Split
1
 
2
 
3
Value
01
-
JAN
-
2016
Index
0
 
1
 
2
Splitted values.

How split() and arrays work

The string array variable "splitDate" receives each portion of the value of "date" that were split apart and allocates storage for each of them. In the table above, the value of the variable "date" was divided into three parts. We can see how many times the value was split in the "Split" row and its corresponding value in the "Value" row. The end of the string automatically cuts the last part which is why we got three portions of the value despite having only two of the delimiter ("-").

Now we have three different values. We need only the first part ("01") for our getDay() method. To get the value we need, we must have a key to the allocated storage specifically for the value "01". Notice the last row called "Index". The first element of an array always starts with the index 0. Since we need the first element, we can get the value "01" using "splitDate[0]" which translates to "the first element of an array named splitDate".

We could easily write "return splitDate[0];" but as previously discussed, the return type of the method getDay() is "int" and therefore the return statement should include a value of type "int" despite of the method accepting a string parameter.

Type mismatch error.
Type mismatch error.

We learned how to parse a string earlier. Now, in order to fix the type mismatch error we encountered in the above image, we must parse an integer from a string using the parseInt() method. To do this, we simply type:

Integer.parseInt(splitDate[0]);

The getDay() method without errors.
The getDay() method without errors.
Results.
Results.

We didn't get the exact value "01", instead we got 1. I will explain and fix that in the next parts but for now, this will be good enough.

Let's do the same for the getMonth() and getYear() methods until we have three working methods that parse the full date. We use the index 1 for getMonth() and 2 for getYear() following the previous table "Splitted values" above.

	public int getDay(String date){
		String[] splitDate = date.split("-");
		
		return Integer.parseInt(splitDate[0]);
	}
	
	public String getMonth(String date){
		String[] splitDate = date.split("-");
		
		return splitDate[1];
	}
	
	public int getYear(String date){
		String[] splitDate = date.split("-");
		
		return Integer.parseInt(splitDate[2]);
	}
Results of all three methods.
Results of all three methods.

Exporting MyCalendar as a JAR file

While our library is not yet complete, let's see if the methods we created will work as a library imported to another package and class. I will assume that you have created a class named "MyCalendar" and written the code below.

public class MyCalendar {
	
	public int getDay(String date){
		String[] splitDate = date.split("-");
		
		return Integer.parseInt(splitDate[0]);
	}
	
	public String getMonth(String date){
		String[] splitDate = date.split("-");
		
		return splitDate[1];
	}
	
	public int getYear(String date){
		String[] splitDate = date.split("-");
		
		return Integer.parseInt(splitDate[2]);
	}
	
}

The following steps were done using Eclipse IDE. Steps may vary depending on which IDE you use but there shouldn't be much difference.

Step 1: In the Package Explorer, right-click the MyCalendar project and click Export.

The Package Explorer.
The Package Explorer.

Step 2: Select JAR file from the Java folder and click Next.

Export JAR file.
Export JAR file.

Step 3: Tick the checkbox beside MyCalendar, select the export destination, and click Finish.

Select export destination.
Select export destination.

Adding the MyCalendar.jar as a library.

Now, we can see if the previously exported MyCalendar JAR file will work as a library. Let us first create another Java project and another sample class. Once it is created, we can add the JAR file into the build path of our new project.


Step 1: Right-click the new project, select Build Path > Configure Build Path.

Configure build path.
Configure build path.

Step 2: In the Libraries tab, click Add External JARs, select the previously exported MyCalendar.jar, and click OK.

Add External JARs.
Add External JARs.

Step 3: You will now see the MyCalendar.jar in the Libraries tab, click OK.

MyCalendar.jar is now added to the new project's libraries.
MyCalendar.jar is now added to the new project's libraries.

Using the library's methods

Let us again create an object of the MyCalendar class to see if it can now act as a library and its methods can be used in our new project. This time let's choose the name "calendar" just to show you that it could be any name as long as it's not a reserved keyword.

When the error in the image below appears, simply choose the "Import 'MyCalendar'" in the 4 quick fixes offered.

Tip

Pressing Ctrl + Shift + O will automatically organize your imports. This includes importing necessary resources and removing unused imports/resources.

MyCalendar cannot be resolved to a type.
MyCalendar cannot be resolved to a type.

Tests

In the code block below, I initialized the variable "date" with the same value as the one we previously tested (01-JAN-2016) then I passed it as an argument to the three methods: getDay(), getMonth(), getYear(). I also passed the string values "26-FEB-1991" and "27-OCT-1984" to see if it works directly with the methods.

I displayed them in a table kind of way, nothing fancy, we just want to see if the outputs are correct regardless of different inputs.

Tips

  • For Eclipse IDE, you can type "syso" then Ctrl + Space as a shortcut for "System.out.println();".
  • For IntelliJ IDEA, type "sout" then Enter.

public class AnotherSample {

	public static void main(String[] args){
		MyCalendar calendar = new MyCalendar();
		String date = "01-JAN-2016";
		
		System.out.println("DAY | MONTH | YEAR ");
		System.out.println(" " + calendar.getDay(date) + "  |  " + calendar.getMonth(date) + "  | " + calendar.getYear(date));
		System.out.println("" + calendar.getDay("26-FEB-1991") + "  |  " + calendar.getMonth("26-FEB-1991") + "  | " + calendar.getYear("26-FEB-1991"));
		System.out.println("" + calendar.getDay("27-OCT-1984") + "  |  " + calendar.getMonth("27-OCT-1984") + "  | " + calendar.getYear("27-OCT-1984"));

	}
	
}
Our neat table.
Our neat table.

End of Part 1

We verified that the library we created works but this is just the beginning. We are still far from a complete calendar library. We are only in part 1 after all. I decided to cut the tutorial into many parts because I want it to be as comprehensive as possible.

Read Part 2

© 2014 Joann Mistica

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.