ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

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

Updated on April 3, 2015

Part 4 - Next month

In Part 3, we created two methods to get the month ID of a given month name and the other way around. We are left with two problems: [1] we are manually adding 1 to get the next month and this can be annoying and not very user-friendly and [2] we get an error every time we try to get the month after December because we did not implement a "reset" where it goes back to January.

In this part, we will discuss:

  • Removing the manual work
  • Fixing the IndexOutOfBoundsException
  • Implementing a "reset to January" for the dates that reach the month of December
  • Using two methods with very specific functions to create another useful method
  • Making methods that are flexible for different date formats in the future

Test for all methods.
Test for all methods. | Source
Method
Purpose
nextMonth()
Returns the month after the given month.
Methods and their purpose.

Problem and solution


Problem #1
We are manually adding 1 to get the month after the given month.

Solution
Instead of manually adding 1 when the method is invoked, we can create a method to do that so the user doesn't have to see how it is manually done.

Problem #2
We get an error every time we try to get the month after December because we did not implement a "reset" where it goes back to January.

Solution
We will implement a "reset" where the month will automatically go back to January once it reaches the last month - December.

public String nextMonth(String date){
	String nextMonth = "";
	
	if (monthID(date) != 12){
		nextMonth = monthName(monthID(date) + 1);
	}
	else
		nextMonth = monthName(1);
	
	return 	nextMonth;
}

Next month

In the code above, I've created the method named nextMonth(). It has the parameter "date" and returns a value of string data type. As you can see, it uses the methods monthID() and monthName() together. The user no longer needs to manually input a month ID and add 1 or use the methods monthID() and monthName() together to get the next month. The nextMonth() method does the work and all the user needs to do is pass a date to the nextMonth() method and it will parse the value of "date", get the month, and return whatever month comes after.

I declared a string variable named "nextMonth" and initialized it with a blank value. The program enters the "if" statement where it checks if the month ID of the given date is not equal to 12 or "DEC". If this condition is satisfied, the value of "nextMonth" will be the month name of the month ID of the given date plus 1.

The nextMonth() method.
The nextMonth() method.

Example

An example below is written to show you the order of what happens in the line of code when the condition is satisfied and how the result is calculated. The underlined parts in each step is the first to be executed, just right below it is the actual result. It has been previously discussed that in a line of code where there are methods within a method, the innermost part is executed first.

We will use the date "03-AUG-2013" as an example of "date" passed to the nextMonth() method.

Code (Underlined): nextMonth = monthName(monthID(date) + 1);
Actual value (Result): date = "03-AUG-2013"

Code (Underlined): nextMonth = monthName(monthID(date) + 1);
Actual value (Result): monthID("AUG") = 8

Code (Underlined): nextMonth = monthName(monthID(date) + 1);
Actual value (Result): 8 + 1 = 9

Code (Underlined): nextMonth = monthName(monthID(date) + 1);
Actual value (Result): monthName(9) = "SEP"

Code (Underlined): nextMonth = monthName(monthID(date) + 1);
Actual value (Result): nextMonth = "SEP"

Let's verify if the way we interpreted the code is correct and try to run the program where the value of "date" is "03-AUG-2013".

Sample Class

System.out.println("Next to " + myCalendar.getMonth(date) + " is " + myCalendar.nextMonth("03-AUG-2013"));
We got "SEP" as expected.
We got "SEP" as expected.

Further Explanation

Since the month ID of "AUG" is 8 instead of 12, the "if" condition was satisfied and just as we expected, the value returned was "SEP".

All other conditions not mentioned under any "if" or "else if" statements will go to the "else" part. Since we only have one "if" and that is if month ID is not equal to 12 or if the given month is not "DEC", we can simply go the opposite for "else" which is if month ID is equal to 12 or if the given month is "DEC".

		else
			nextMonth = monthName(1);

In the code above, if the month ID is equal to 12 or the given month is December, the "nextMonth" variable will have the value of "monthName(1)" or "JAN". This is the reset part. There are only twelve months in a year, there is really no next month after December, the next month is simply the first January of the next year.

Why did I use the month ID instead of the month name? Why didn't I just put 'if the given month is "DEC" or nextMonth = "JAN"'?


Why this?

if (monthID(date) != 12){
nextMonth = monthName(monthID(date) + 1);
}
else
nextMonth = monthName(1);

Why NOT this?

if (!monthName(date).equals("DEC")){
nextMonth = monthName(monthID(date) + 1);
}
else
nextMonth = "JAN";

I mentioned in Part 1 of this article that we will first use the format "DD-MON-YYYY" for all dates and create different formats later on. If I put "DEC" or the month name, the code will automatically generate an error for any other formats where the month name is not "DEC". Using the month ID is more flexible since every month has a unique ID regardless of its format. Therefore, we do not need to start all over again or adjust our code each time we add a new format.

I assume that you've written the code below for the "MyCalendar" class or added the code for the nextMonth() method to our previous code.

MyCalendar

	public String nextMonth(String date){
		String nextMonth = "";
		
		if (monthID(date) != 12){
			nextMonth = monthName(monthID(date) + 1);
		}
		else
			nextMonth = monthName(1);
		
		return 	nextMonth;
	}

SampleClass

Below are some samples to test the results of the nextMonth() method.

public class SampleClass {
	
	public static void main(String[] args) {
		MyCalendar myCalendar = new MyCalendar();
		
		System.out.println("Next to " + "JAN" + " is " + myCalendar.nextMonth("01-JAN-2016"));
		System.out.println("Next to " + "FEB" + " is " + myCalendar.nextMonth("26-FEB-1991"));
		System.out.println("Next to " + "MAR" + " is " + myCalendar.nextMonth("03-MAR-2013"));
		System.out.println("Next to " + "APR" + " is " + myCalendar.nextMonth("08-APR-1868"));
		System.out.println("Next to " + "MAY" + " is " + myCalendar.nextMonth("11-MAY-2001"));
		System.out.println("Next to " + "JUN" + " is " + myCalendar.nextMonth("21-JUN-2011"));
		System.out.println("Next to " + "JUL" + " is " + myCalendar.nextMonth("15-JUL-1998"));
		System.out.println("Next to " + "AUG" + " is " + myCalendar.nextMonth("03-AUG-2013"));
		System.out.println("Next to " + "SEP" + " is " + myCalendar.nextMonth("30-SEP-2005"));
		System.out.println("Next to " + "OCT" + " is " + myCalendar.nextMonth("27-OCT-1984"));
		System.out.println("Next to " + "NOV" + " is " + myCalendar.nextMonth("06-NOV-2003"));
		System.out.println("Next to " + "DEC" + " is " + myCalendar.nextMonth("04-DEC-1879"));
	}
}
The result after running the samples for the "nextMonth()" method.
The result after running the samples for the "nextMonth()" method.

The method is now able to return the next month for months starting from January to December and we no longer encounter the IndexOutOfBoundsException like we did in the previous code because of the "reset" we've added to the code.

Important note

The codes above simply serve as a summary of what we have discussed in Part 4. 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 4

We have created a new method where we utilized two different methods with very specific purposes - monthName() and monthID(). We also fixed the IndexOutOfBoundsException we used to encounter and we are no longer manually adding 1 to get the next month.

However, our journey from December to January still isn't flawless. The only purpose of the nextMonth() is of course, to get the next month. This can be confusing if for example, we tried to get the next month after "December 2014", we should be given the result "January 2015".

In the next part, we will create a method to get the next year and while we're at it, we will create a method to get the next day as well.

Read Part 5

© 2015 Joann Mistica

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)