Sample Java custom date conversion class

  • 2020-04-01 03:23:21
  • OfStack

Java custom date conversion class


import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.beanutils.Converter;

public class MyDateConverter implements Converter {
 @Override
 //Convert value to c corresponding type
 //There is a Class argument for writing a universal converter, and if the conversion target type is determined, the c argument may not be used
 public Object convert(Class c, Object value) {
  String strVal = (String) value;
  //To convert String to Date -- requires Date formatting
  DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
  try {
   Date date = dateFormat.parse(strVal);
   return date;
  } catch (ParseException e) {
   e.printStackTrace();
  }
  return null;
 }
}


Related articles: