---
title: "struts2的时间格式转换问题"
author: "jolestar"
date: "2008-03-21T11:50:07Z"
tags: ["Apache", "Java", "Struts", "log4j", "框架"]
categories: ["企业架构"]
slug: "struts2"
draft: false
lastmod: "2008-03-21T11:50:07Z"
id: 174444
url: "https://jolestar.iteye.com/blog/174444"
---

struts2提供了一个时间标签:

```
<s:date name="todayDate" format="yyyy-MM-dd" />
```

   但这个标签很只能在显示的时候用，但如果我想在输入框里显示时间，让用户直接修改时间，怎么弄？datepicker？选择太麻烦，我想让用户输入，并且兼容多种日期格式。还有，如果用时间标签的话，每个地方都需要指定format，如果我想修改一下格式，所有的时间显示都变，怎么弄？

 

翻了一下struts2的源码，和文档，找到一个办法。  com.opensymphony.xwork2.util.XWorkConverter

```
 * <p/> In some situations you may wish to apply a type converter globally. 
 *  This can be done by editing the file
 * <b>xwork-conversion.properties</b> in the root of your class path 
 * (typically WEB-INF/classes) and providing a
 * property in the form of the class name of the object you wish to convert 
 * on the left hand side and the class name of
 * the type converter on the right hand side. For example, providing 
 * a type converter for all Point objects would mean
 * adding the following entry:
 *
 * <p/><b>com.acme.Point = com.acme.PointConverter</b>
```

 

XWorkConverter，先在classpath root下找xwork-conversion.properties文件，这个文件定义了全局转换。然后每遇到新的类需要转换，便查找是否有特殊的自定义转换配置。特殊自定义转换配置文件的路径是:

```
className.replace('.', '/') + "-conversion.properties";
```

 比方com.acme.Point的转换配置就是classpath 下的/com/acme/Point-coversion.properties文件。

 

ok，这个问题好解决了。

 

我的xwork-coversion.properties文件:

```
java.util.Date=cn.jolstar.struts.type.DateTypeConverter
```

 我的DateTypeConverter代码:

```
/**
 * 
 */
package cn.jolestar.struts.type;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.struts2.util.StrutsTypeConverter;


/**
 * @author jolestar
 * 
 */
public class DateTypeConverter extends StrutsTypeConverter {

	private static final Logger log = Logger.getLogger(DateTypeConverter.class);
	public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
	
	//暂时只考虑这几种日期格式
	public static final DateFormat[] ACCEPT_DATE_FORMATS = {
			new SimpleDateFormat(DEFAULT_DATE_FROMAT),
			new SimpleDateFormat("yyyy年MM月dd日"),
			new SimpleDateFormat("yyyy/MM/dd") };

	/**
	 * 
	 */
	public DateTypeConverter() {
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.apache.struts2.util.StrutsTypeConverter#convertFromString(java.util.Map,
	 *      java.lang.String[], java.lang.Class)
	 */
	@Override
	public Object convertFromString(Map context, String[] values, Class toClass) {
		if (values[0] == null || values[0].trim().equals(""))
			return null;
		for (DateFormat format : ACCEPT_DATE_FORMATS) {
			try {
				return format.parse(values[0]);
			} catch (ParseException e) {
				continue;
			} catch (RuntimeException e) {
				continue;
			}
		}
		log.debug("can not format date string:" + values[0]);
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.apache.struts2.util.StrutsTypeConverter#convertToString(java.util.Map,
	 *      java.lang.Object)
	 */
	@Override
	public String convertToString(Map context, Object o) {
		if (o instanceof Date) {
			SimpleDateFormat format = new SimpleDateFormat(
					DEFAULT_DATE_FORMAT);
			try {
				return format.format((Date) o);
			} catch (RuntimeException e) {
				return "";
			}
		}
		return "";
	}

}
```

 

 

 

这样，从字符串转换为日期对象的时候，会尝试上面列出的多种日期格式，但输出的时候，则会统一按照DEFAULT—DATE—FORMAT转换。 需要修改格式，只需要修改DEFAULT—DATE—FORMAT。当然，你也可以把它方在配置文件里，便于修改。

 

了解了这一点，其实也就 明白了struts的类型转换模式。然后，无论是字符串id到持久化对象的转换，还是自定义的字符串到对象之间的转换，都容易了。