struts-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Li Ying <liying.cn.2...@gmail.com>
Subject Re: Struts 2 date field problem
Date Wed, 12 Oct 2011 01:36:58 GMT
Did your problem happens when date input or output?

For output case, the <s:date> tag can let you choose the format to use.
See:
http://struts.apache.org/2.x/docs/date.html

For input case, Struts2 can convert HTTP parameters from String into
most of data type you need, include Date.

But for Date, it [uses the SHORT format for the Locale associated with
the current request]

So, if your parameters can not be converted to Date correctly, maybe you need:
(1)change your input format
(2)or build a new Type Converter to support the format you want.

This page describes the details:
http://struts.apache.org/2.x/docs/type-conversion.html

And, the following code is a DateConverter we used in our project,
which support several date formats:

================= START =================
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.util.StrutsTypeConverter;

public class DateConverter extends StrutsTypeConverter {
	private String[] dateFormats = new String[] {
			"yyyy/MM/dd HH:mm:ss",
			"yyyy/MM/dd" };

	@Override
	@SuppressWarnings("rawtypes")
	public Object convertFromString(final Map context, final String[] values,
			final Class toClass) {
		String dateStr = values[0];

		if (StringUtils.isEmpty(dateStr)) {
			return null;
		}

		for (String formatStr : dateFormats) {
			SimpleDateFormat format = new SimpleDateFormat(formatStr);
			try {
				return format.parse(dateStr);
			} catch (ParseException e) {
			}
		}

		throw new RuntimeException("Could not parse date. [" + dateStr + "]");
	}

	@Override
	@SuppressWarnings("rawtypes")
	public String convertToString(final Map context, final Object o) {
		return o.toString();
	}
}
================= END =================




2011/9/29  <karthick.gunasekaran@wipro.com>:
> I want to get the struts 2 date field as Date,
>
> But it return the string value,
>
> My bean property is date data type any way Is there to directly get the
> date data type from struts 2 date tag
>

---------------------------------------------------------------------
To unsubscribe, e-mail: user-unsubscribe@struts.apache.org
For additional commands, e-mail: user-help@struts.apache.org


Mime
View raw message