public static Object convertStringToObject(String value, Class<?> toType) { try { DateConverter dc = new DateConverter(); dc.setUseLocaleFormat(true); dc.setPatterns(new String[] {"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss"}); ConvertUtils.register(dc, Date.class); return ConvertUtils.convert(value, toType); } catch (Exception e) { throw convertReflectionExceptionToUnchecked(e); } }
/** * 转换字符串类型到 toType 类型, 或 toType 转为字符串 * * @param value: 待转换的字符串 * @param toType: 提供类型信息的 Class, 可以是基本数据类型的包装类或指定格式日期型 * @return */ public static <T> T convertValue(Object value, Class<T> toType) { try { DateConverter dc = new DateConverter(); dc.setUseLocaleFormat(true); dc.setPatterns(new String[] {"yyyy-MM-dd", "yyyy-MM-dd hh:mm:ss"}); ConvertUtils.register(dc, Date.class); return (T) ConvertUtils.convert(value, toType); } catch (Exception e) { e.printStackTrace(); throw convertToUncheckedException(e); } }
/** * 定义Apache BeanUtils日期Converter的格式,可注册多个格式,以','分隔. * * @param patterns the patterns */ public static void registerDateConverter(String... patterns) { DateConverter dc = new DateConverter(); dc.setUseLocaleFormat(true); dc.setPatterns(patterns); ConvertUtils.register(dc, Date.class); }
private static void registerDateConverter() { DateConverter dc = new DateConverter(); dc.setUseLocaleFormat(true); dc.setPatterns(new String[] {"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss"}); org.apache.commons.beanutils.ConvertUtils.register(dc, Date.class); }
static { DateConverter dc = new DateConverter(); dc.setUseLocaleFormat(true); dc.setPatterns(new String[] {"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss"}); ConvertUtils.register(dc, Date.class); }