Struts2 compatible date type converter (yyyy-MM-dd or yyyy/MM/dd or yyyyMMdd)

I want to say to myself: Since it has already started, I will die quietly.

Reprinted source: Power Node-SSH from entry to master

package converter;

import java.util.Date;
import java.text.SimpleDateFormat;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.conversion.TypeConversionException;
import com.opensymphony.xwork2.conversion.impl.DefaultTypeConverter;
import com.sun.org.apache.xalan.internal.xsltc.compiler.Pattern;

public class MyDateConverter extends DefaultTypeConverter {

	@SuppressWarnings("unchecked")
	@Override // value:目标转换值;toType:目标转换类型
	public Object convertValue(Object value, Class toType) {
		SimpleDateFormat sdf = null; // 创建空的简单日期格式
		try {
			if (Date.class == toType) { // 前端页面到服务器端的数据转换
				String dateStr = ((String[]) value)[0];
				sdf = getSimpleDateFormat(dateStr); // 调用自定义简单日期格式转换函数
				ActionContext.getContext().getSession().put("sdf", sdf); // 将返回的日期格式存入Session会话
				return sdf.parse(dateStr); // 返回日期格式的解析结果
			} else if (String.class == toType) { // 服务器端到前端页面的数据转换
				Date date = (Date)value;
				// 从Session会话中获取存储的日期格式
				sdf = (SimpleDateFormat)ActionContext.getContext().getSession().get("sdf");
				return sdf.format(date);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return super.convertValue(value, toType); // 返回最终的日期格式转换结果
	}

	/**
	 * 根据传入的参数生成指定的日期格式
	 * @param source
	 * @return
	 */
	private SimpleDateFormat getSimpleDateFormat(String source) {
		SimpleDateFormat sdf = null;
		if (Pattern.matches("^\\d{4}-\\d{2}-\\d{2}$", source)) {
			sdf = new SimpleDateFormat("yyyy-MM-dd");
		} else if (Pattern.matches("^\\d{4}/\\d{2}/\\d{2}$", source)) {
			sdf = new SimpleDateFormat("yyyy/MM/dd");
		} else if (Pattern.matches("^\\d{4}\\d{2}\\d{2}$", source)) {
			sdf = new SimpleDateFormat("yyyyMMdd");
		} else {
			throw new TypeConversionException(); 
		}
		return sdf;
	}
	
}

Learning is like walking. After walking for a long time, the body is naturally warm and comfortable, and the brain is naturally bright when thinking more.

Ordinary people, don't talk about perseverance, just want to see the flat or rising data from the input method feedback to them every day and feel at ease!

Enter hard too today ❤!

Guess you like

Origin blog.csdn.net/qq_44965393/article/details/111879122