应用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;//生成日期字符串,格式为-8-8return 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" "/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>格式为:-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" "/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=".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日”
如果觉得《将Calendar对象转换为日期时间字符串》对你有帮助,请点赞、收藏,并留下你的观点哦!