用webwork的datepicker时, 如果格式是"%Y-%m-%d"工作很正常, 但是有些格式需要带上时间的:
"%Y-%m-%d %H:%M", 这时用webwork默认的类型转换就不行了,需要自己实现, 根据javaeye论坛某高手的建议用正则表达式来判断form传过来的日期字符串是"%Y-%m-%d"还是"%Y-%m-%d %H:%M",再用相应的SimpleDateFormat来parse分析字符串生成Date对象, 代码如下:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import org.apache.log4j.Logger;
import com.opensymphony.webwork.util.WebWorkTypeConverter;
public class DateConverter
extends WebWorkTypeConverter
{
private static final Logger log = Logger.getLogger( DateConverter.class );
private final static String regex_time = "[0-9]{2,4}-[0-9]{1,2}-[0-9]{1,2} [0-9]{1,2}:[0-9]{1,2}";
private final static SimpleDateFormat sdf_time = new SimpleDateFormat(
"yyyy-MM-dd HH:mm" );
private final static String regex_date = "[0-9]{2,4}-[0-9]{1,2}-[0-9]{1,2}";
private final static SimpleDateFormat sdf_date = new SimpleDateFormat(
"yyyy-MM-dd" );
@Override public Object convertFromString( Map context, String[] values,
Class toClass )
{
if ( values.length == 1 )
{
Date date = null;
try
{
date = convertToDate( values[0] );
}
catch ( ParseException e )
{
log.warn( e.getMessage() );
}
return date;
}
Date[] results = new Date[values.length];
for ( int i = 0; i < values.length; i++ )
{
String value = values[i];
try
{
results[i] = convertToDate( value );
}
catch ( ParseException e )
{
log.warn( e.getMessage() );
}
}
return results;
}
private Date convertToDate( String value )
throws ParseException
{
if ( value.matches( regex_time ) )
return sdf_time.parse( value );
else if ( value.matches( regex_date ) )
return sdf_date.parse( value );
return null;
}
@Override public String convertToString( Map context, Object o )
{
if ( o instanceof Date )
{
Date date = (Date) o;
return sdf_time.format( date );
}
return o.toString();
}
public static void main( String[] args )
{
System.out.println( "2006-07-11".matches( regex_date ) );
System.out.println( "2006-07-11 00:21".matches( regex_time ) );
}
}
要让这个类来代替webwork默认的转换你还需要在classpath目录, 一般就是classes目录放置配置文件
xwork-conversion.properties:
java.util.Date=DateConverter 这种方法是对整个application起作用,.
如果要只对单个action起作用, 在action同一个package写一个ActionClassName-conversion.properties:
startDate=DateConverter