Developer

Using dates with JavaServer Pages

Handling dates and times is a challenge to many developers, but Java provides all the functionality you'll need for almost any calendar-based application.


The irregular number of days in each month, seven-day weeks, and weekends present an obstacle for almost any calendar-based application. As a result, working with dates and times often appears daunting to novice programmers. This article will demonstrate the utilization of dates within a JavaServer Pages (JSP) application and will provide a handy reference for some common tasks.

Objective
The goals of this sample application are to:
  • ·        Pass a date to a processing page from an HTML form.
  • ·        Receive the date and create a Calendar object.
  • ·        Use the Calendar object to find out whether the date is a weekend day, which day of the week the date is, and how many working days are in the selected month.
  • ·        Format the date in an easily readable display for users.

Environment
The example code has been tested on a Java Web Server configured to use JDK 1.31. The examples are quite standard, though, and will work just as well on Tomcat or just about any other JSP-enabled Web server (JDK 1.2 or higher).

Passing a date to a JSP page from a form
Date parameters are user-selected from three drop-down lists. These parameters are sent to a processing page when the user submits the form.

When working with calendars, don’t forget to importjava.util.Calendar:
<%@ page import="java.util.Calendar" %>

The first task of the processing page is to receive the date values for Date, Month, and Year.
int curDate = 1;
if(request.getParameter("curDate") != null)
{
curDate = Integer.parseInt(request.getParameter("curDate"));
}

Note that the page parameters are converted to int. We will soon see why.

The Calendar object
Our objective is to create and set up a Calendar object we can use to perform our calculations. To do this, we will need to instantiate a Calendar object.
Calendar cal  = Calendar.getInstance();

Calendar.getInstance() returns a Calendar object that represents the current date and time.
cal.clear();
cal.set(curYear, curMonth , curDate);

Using the clear() method clears the Calendar, making it possible for us to assign our own values to the object and to make it ready for any calculations we may need to do. Note the order of the parameters: year first and date last.

Getting information from the Calendar
Here is a set of Calendar fields.

Dates 
DATE, DAY_OF_MONTH, DAY_OF_WEEK, DAY_OF_YEAR

Times 
HOUR_OF_DAY, MINUTE, MILLISECOND, SECOND

Weeks 
WEEK_OF_MONTH, WEEK_OF_YEAR

Year 
YEAR

Each of these fields can be accessed via the Calendar’s get() method, which returns an integer. The following code samples demonstrate this.

Day of the week 
int dayOfWeek = cal.get(cal.DAY_OF_WEEK);
out.print("<br>Day of Week: " + dayOfWeek + " <br>");

Day of the month 
int dayOfMonth = cal.get(cal.DAY_OF_MONTH);
out.print("<br>Day of Month: " + dayOfMonth + " <br>");

Locating specific days
To find a particular day in the week, it is necessary to access the DAY_OF_WEEK field. The field contains integer values from 1 to 7, with 1 representing Monday, 2 for Tuesday, and so on.
int dayOfWeek = cal.get(cal.DAY_OF_WEEK);

A useful way to display the day to the user is to declare an array that contains the days of the week. It is then easy to display the day. Simply use the DAY_OF_WEEK integer to access the correct day in the array.
String[] weekdays = new String[]
{“”, "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
<%=weekdays[cal.get(cal.DAY_OF_WEEK)]%>

Note that the first element of the array is empty. This is done because the DAY_OF_WEEK field’s values are from 1 to 7, while the array index goes from 0 to 6. By adding the empty element at the beginning of the array, we ensure that the DAY_OF_WEEK field’s values and the array index match up.

Locating weekends
To find out if a particular day is a Saturday or Sunday, use the following:
int day = cal.get(cal.DAY_OF_WEEK);
if(day == 6 || day == 7)
{
//Perform weekend-specific actions
}

Working days
Now, we need to calculate the number of working days in a particular month. The user enters the date (see index.jsp) and sends it to the processing page (see display.jsp). On the processing page, we will set the Calendar object to the first day of the month.
cal.clear();
cal.set(curYear, curMonth , 1);
int maxDays = cal.getActualMaximum(cal.DATE);
out.print("<br>Number of days in month: " + maxDays + "<br>");

We also need to know how many days there are in a particular month. The getActualMaximum() method returns an integer value that contains the maximum number of days in the month—28 for February, 31 for March, and so on. Naturally, the month of February returns 29 days on a leap year.

Once we have the maximum number of days in the month, we can easily loop through the days to whether each one is a weekend or working day. We use the add() method to increment the Calendar object, as you can see in Listing A.

Displaying dates to the user using SimpleDateFormat
SimpleDateFormat handles the most common requirements relating to displaying the date, as well as being useful for converting dates to specific storage formats. Use the following import directive:
<%@ page import="java.text.SimpleDateFormat" %>

The following code displays the date to the user:
SimpleDateFormat formatter = new SimpleDateFormat("dd/MMM/yyyy");
out.print("<br>" + formatter.format(cal.getTime())  );

The SimpleDateFormat object accepts as its constructor a string that contains the intended format for display. The format string can contain additional formatting characters, such as space, (“ ”), forward slash (“/”), and dash (“-”).

Table A lists all valid (and commonly used) display formats,
Table A

Format

Example

“dd/MMM/yyyy”

06/Mar/1974

"dd-MM-yyyy"

06-03-1974

"dd MMMMMMMMM yyyy"

06 March 1974

"EEEEEEEEE, MMMMMMMMM dd, yyyy"

Wednesday, March 06, 1974

Valid SimpleDateFormat display formats

Table B offers an abbreviated list of SimpleDateFormat parameters.
Table B
y year
M month in year
d day in month
D day in year
w week in year
W week in month
E day in week
SimpleDateFormat parameters

Reusable code—FormatTitle
An easy way to perform multiple conversions on the same page is to declare a method in a Declaration element. The FormatTitle method accepts two parameters—a reference to the Calendar object and the return format.
<%!
public String FormatTitle(Calendar fCal, String format)
{
SimpleDateFormat formatter = new SimpleDateFormat(format);
return (formatter.format(fCal.getTime() ));
}
%>

To display the date, we call FormatTitle() and pass the Calendar and format string.
<%=FormatTitle(cal, “dd-MMM-yyyy”)%>

Conclusion
Having worked through this tutorial, you should now be able to manipulate and display dates using the Calendar and SimpleDateFormat objects.

The add() and set() methods enable easy configuration of a Calendar, allowing you to loop through months or years for business applications. The FormatTitle method can greatly simplify the task of displaying dates to the user or of converting a date into a string for storage purposes in a database or XML document.

Editor's Picks

Free Newsletters, In your Inbox