Java basics-date usage in JSP

Source: Internet
Author: User
Tags days in month
Java basics-Brief Introduction to date usage in JSP-general Linux technology-Linux programming and kernel information. The following is a detailed description. Purpose




The purpose of the sample application is:


Submit the date parameter to a JSP page through an HTML form.

Receives the date parameter and creates a Calendar Object.

Use the Calendar Object to find out the day of the week to be submitted and the number of working days in the selected month.

Format the date in an easy-to-read display format.


Environment


The sample code is tested on the Java Web server, which is configured with JDK 1.31. The example is well written, and the running effect on Tomcat or other JSP Web servers (JDK 1.2 or later) is almost identical.


Pass the date to the JSP page through the form


The Date parameter is selected from the drop-down list in the "3" column. After a user submits a form, these parameters are transmitted to the processing page.


Do not forget to import java. util. Calendar during Calendar programming:

<% @ Page import = "java. util. Calendar" %> 〉


The 1st tasks on the processing page receive the following Date parameter values: 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 the int type, so we will know why.




Calendar Object


Our goal is to create and set a Calendar Object for date calculation. Therefore, we need to instantiate a Calendar Object first.

Calendar cal = Calendar. getInstance ();


Calendar. getInstance () returns a Calendar Object that represents the current date and time.

Cal. clear ();

Cal. set (curYear, curMonth, curDate );


The clear () method clears the Calendar, so that we can allocate our own date value to this object and prepare for future computation. Note the order of these parameters: Year and date.




Obtain information from Calendar


The following is a set of Calendar fields:


Date

DATE, DAY_OF_MONTH, DAY_OF_WEEK, DAY_OF_YEAR


Time

HOUR_OF_DAY, MINUTE, MILLISECOND, SECOND


Week

WEEK_OF_MONTH, WEEK_OF_YEAR


Year

YEAR


All the above fields can be accessed through the get () method of the Calendar, and an integer is returned. The following code example shows the preceding process.


Date of the week

Int dayOfWeek = cal. get (cal. DAY_OF_WEEK );

Out. print ("<br> Day of Week:" + dayOfWeek + "<br> 〉");


Date of January 1, January

Int dayOfMonth = cal. get (cal. DAY_OF_MONTH );

Out. print ("<br> Day of Month:" + dayOfMonth + "<br> 〉");


Locate a specific date




To locate a specific day in a week, you must access the DAY_OF_WEEK field. This field contains an integer ranging from 1 to 7. 1 indicates Monday, 2 indicates Tuesday, and the rest are similar.

Int dayOfWeek = cal. get (cal. DAY_OF_WEEK );


Here is a good way to display the date to the user, that is, to declare an array containing the number of days in a week. Then you can easily display each date. You only need to use the current date in the DAY_OF_WEEK integer week number group.

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 null. This is because the value range of the DAY_OF_WEEK field is from 1 to 7, and the reference range of the array element is from 0 to 6. Adding an empty element at the beginning of the array ensures that the value of the DAY_OF_WEEK field matches the array reference.




Find the weekend

You can write the following code to find out whether the day is Sunday or Saturday:

Int day = cal. get (cal. DAY_OF_WEEK );

If (day = 6 | day = 7)

{

// Perform weekend-related operations

}




Workday


Now we need to calculate the number of working days in a month. After the user enters the date (see index. jsp), the parameter is sent to the processing page (see display. jsp ). On the processing page, we set the Calendar Object to the 1st 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 the number of days in a month. The getActualMaximum () method returns an integer that contains the maximum number of days per month: January 1, and 31. In a leap year, the number of days in January 29 is returned.


Once we get the maximum number of days per month, we can easily cycle the number of days per month to determine whether it is a weekend or a day of work. We use the add () method to increase the value of Calendar by 1, as shown in program list.




Use SimpleDateFormat to display the date to the user


SimpleDateFormat is the most common requirement for processing the display date. It can be used to convert the date to a specific save format. You can use the following import indicator:

<% @ Page import = "java. text. SimpleDateFormat" %> 〉


Run the following code to display the date:

SimpleDateFormat formatter = new SimpleDateFormat ("dd/MMM/yyyy ");

Out. print ("<br>" + formatter. format (cal. getTime ()));


The SimpleDateFormat object accepts a string as its object constructor. This string parameter contains the desired display format. This format string can contain additional format strings, such as spaces (""), backslash ("/"), and break signs ("-").


Table A lists all valid (commonly used) display formats.


Table


Format

Example


"Dd/MMM/yyyy"

06/Mar/1974


"Dd-MM-yyyy"

06-03-1974


"Dd Mmmmmmm yyyy"

06 March 1974


"EEEEEEEEE, Mmmmmmm dd, yyyy"

Wednesday, March 06,197 4



Valid SimpleDateFormat display format




Table B is the abbreviation of the SimpleDateFormat parameter.


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 Parameter



Code reuse-FormatTitle


There is a simple method to implement multiple format conversions on the same page: The FormatTitle Declaration method is used in the Declaration element. It accepts two parameters, one referencing the Calendar Object and the other returning 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 parameters for it.

<%= FormatTitle (cal, "dd-MMM-yyyy") %> 〉



Summary


After learning the above simple tutorial, I believe you can use the Calendar and SimpleDateFormat objects to operate and display dates now.


The add () and set () methods allow you to easily configure the Calendar AR, so that you can traverse the month and number of years for business applications. The FormatTitle method can greatly simplify the tasks for displaying dates to users. Similarly, it also simplifies the conversion of dates into strings, this operation is mainly used to store data in databases and XML documents.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.