应用Calendar类的get()方法,可以获得Calendar对象中的年月日
JavaBean类
public class StringUtil2 {
private String dateStr; //日期字符串
private Calendar calendar=null;
public String getDateStr() {
int year=calendar.get(calendar.YEAR); //获得年
int month=calendar.get(calendar.MONTH); //获得月
int date=calendar.get(calendar.DAY_OF_MONTH); //获得日
dateStr=year+"-"+month+"-"+date; //生成日期字符串,格式为2008-8-8
return dateStr;
}
public void setDateStr(String dateStr) {
this.dateStr = dateStr;
}
public Calendar getCalendar() {
return calendar;
}
public void setCalendar(Calendar calendar) {
this.calendar = calendar;
}
}
index.jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="tocalendar2.jsp" method="post">
<table>
<tr>
<td align="right">请输入日期字符串:</td>
<td><input type="text" name="datestr">
<font>格式为:2008-08-08</font>
</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="转换"></td>
</tr>
</table>
</form>
</body>
</html>
tocalendar2.jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page language="java" import="java.util.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
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 c=Calendar.getInstance(); //创建一个Calendar对象
c.set(y,m,d); //设置Calendar对象的年月日
%>
<jsp:useBean id="strBean" class="com.cn.zj.bean.StringUtil2"></jsp:useBean>
<jsp:setProperty property="calendar" name="strBean" value="<%=c %>"/>
<table>
<tr>
<td align="right">转换为日期字符串:
</td>
<td>
<jsp:getProperty property="dateStr" name="strBean"/>
</td>
</tr>
</table>
</body>
</html>
有时需要将Calendar对象转换为不同格式的日期时间字符串,格式可能为"yyyy-mm-dd",“yyyy-mm-dd hh:mm:ss”,“yyyy/mm/dd”,“yyyy年mm月dd日”