Making Use of Built In Date/Time Methods

 

Introduction.  We have already made use of some built in date and time functions when working with Java applets and applications.  We will do a couple more examples within the JSP framework.

Say Good Morning.  Now you will learn to get the computer to tell you good morning even if neither you nor it "feels" like it.  I often like to joke that far too many people would prefer to interact with computers that were programmed to say whatever they want!  Anyway, you should develop the following time_of_day.jsp.

 

<html>
<head>
<!-- This is an HTML comment -->
<!-- This is the title of the page that shows up on the browser bar not the page -->

<title>Time of Day</title>
</head>

<body bgcolor="00aa00" text="0000aa">
<%
/* rather than importing the package
we put it in the declaration */

java.util.Calendar current_time = new java.util.GregorianCalendar();
String time_of_day = "";
// checking the hour of the current time to determine
// it is morning, afternoon or other
if (current_time.get(current_time.HOUR_OF_DAY) < 12)
{

time_of_day = "Morning!";

}
else if (current_time.get(current_time.HOUR_OF_DAY) < 18)
{

time_of_day = "Afternoon!";

}
else
{

time_of_day = "Who Knows!";

}
%>

<center><h2>Good <%= time_of_day %></h2></center>
</body>
</html>

 

Notice the Java comments are the same.

When you

  • save this code into a file
  • upload it to a your directory on jasperations.net
  • access the page via a web browser

You should see something like the following.

 

 

Current Date.  Now we will use built in Java functions to parse out the date and display it.  You should call this current_date.jsp.

 

<html>
<head>
<title>Using a Built In Method to Parse the Date</title>
</head>

<body bgcolor="0000aa" text="00aa00">
<%
/* rather than importing the package
we put it in the declaration */

java.util.Calendar current_date = new java.util.GregorianCalendar();

// adding 1 to the month because it starts at 0
int current_month = current_date.get(current_date.MONTH) + 1;
// obtaining day and year
int current_day = current_date.get(current_date.DAY_OF_MONTH);
int current_year = current_date.get(current_date.YEAR);

%>

<font size=4><center>The current date in short format is <BR></center></font>
<font size=5 color="cccccc"><center><b><%= current_month %>/<%= current_day %>/<%= current_year %></b></center></font>
</body>
</html>

 

In this instance I have used the <%= and %> tag pair to display the values.

Your output should look something like the following.