StringUtil.java
package com.lh.bean;
import java.util.Calendar;
public class StringUtil {
// 日期字符串
private String dateStr;
// 将字符串转换后的Calender对象
private Calendar calendar = null;
public String getDateStr() {
// 获得年
int year = calendar.get(calendar.YEAR);
// 获得月
int month = calendar.get(calendar.MONTH) + 1;
// 获得日
int date = calendar.get(calendar.DAY_OF_MONTH);
// 生成日期字符串,格式为2008-8-8
dateStr = year + "-" + month + "-" + date;
return dateStr;
}
public Calendar getCalendar() {
return calendar;
}
public void setDateStr(String dateStr) {
this.dateStr = dateStr;
}
public void setCalendar(Calendar calendar) {
this.calendar = calendar;
}
}
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
<head>
<title>index.jsp</title>
</head>
<body>
<form action="tocalendar.jsp" method="post">
<table>
<tr>
<td align="right">请输入日期字符串:</td>
<td><input type="text" name="datestr" /> <font>格式为:2008-08-08</font>
</td>
</tr>
<tr>
<td colsan="2" align="center"><input type="submit" value="转换" />
</td>
</tr>
</table>
</form>
</body>
</html>
tocalendar.jsp
<%@page import="org.apache.taglibs.standard.tag.el.sql.DateParamTag"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
<head>
<title>check.jsp</title>
</head>
<body>
<%
request.setCharacterEncoding("UTF-8");
String dateStr = request.getParameter("datestr");
//根据"-"分隔字符串为数组
String date[]=dateStr.split("-");
//获得字符串中的年、月、日
int y=Integer.parseInt(date[0]);
int m=Integer.parseInt(date[1]);
int d=Integer.parseInt(date[2]);
//创建一个Calendar对象
Calendar c=Calendar.getInstance();
//设置Calendar对象的年月日
c.set(y, m-1,d);
%>
<!-- 使用useBean动作标签导入JavaBean对象 -->
<jsp:useBean id="strBean" class="com.lh.bean.StringUtil"></jsp:useBean>
<!-- 对StringUtil类的calendar属性赋值 -->
<jsp:setProperty property="calendar" name="strBean"
value="<%=c %>" />
<table>
<tr>
<td align="right">转换为日期的字符串:</td>
<td>
<!-- 从StringUtil对象中获得dateStr的属性值 --> <jsp:getProperty
property="dateStr" name="strBean" /></td>
</tr>
</table>
</body>
</html>