在struts2.0中指定日期的输入输出格式

一般不要用struts默认的日期转换.布置的系统环境决定了struts2怎么来转.这样很没底

自定义日期转换:


1. xwork-conversion.properties里配
java.util.Date=app07.converter.MyDateConverter

 

2.在web.xml里面指定初始化参数datePattern

 

 <context-param>
  <param-name>datePattern</param-name>
  <param-value>yyyy-MM-dd</param-value>
 </context-param>

 

自己写个MyDateConverter

 

package app07b.converter; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; import javax.servlet.ServletContext; import org.apache.struts2.StrutsStatics; import ognl.DefaultTypeConverter; import com.opensymphony.xwork2.util.TypeConversionException; public class MyDateConverter extends DefaultTypeConverter { public Object convertValue(Map context, Object value, Class toType) { ServletContext servletContext = (ServletContext)context.get(StrutsStatics.SERVLET_CONTEXT); String datePattern = servletContext.getInitParameter("datePattern"); System.out.println("date pattern:" + datePattern); if (toType == String.class) { DateFormat format = new SimpleDateFormat(datePattern); return format.format(value); } else if (toType == Date.class) { DateFormat format = new SimpleDateFormat(datePattern); format.setLenient(false); try { String[] s = (String[]) value; Date date = format.parse(s[0]); return date; } catch (ParseException e) { System.out.println("Error:" + e); throw new TypeConversionException("Invalid conversion"); } } return null; } } 

 

你可能感兴趣的:(在struts2.0中指定日期的输入输出格式)