一、前言
基于java.lang.reflect.*反射机制定义对象转换工具类,实现POJO持久化实体和DTO传值对象间相互转换 - 单对象通过源对象及目标class类进行pojoDtoConvertor相互转换(POJO<->DTO)、集合对象转换通过源对象序列及目标class类进行pojoDtoCollectionConvertor相互转换(List<POJO> <-> List<DTO>)、源对象和目标对象pojoDtoConvertor相互转换(POJO<->DTO)。
二、代码示例
import java.lang.reflect.Field;@b@import java.lang.reflect.InvocationTargetException;@b@import java.lang.reflect.Method;@b@import java.math.BigDecimal;@b@import java.util.ArrayList;@b@import java.util.Date;@b@import java.util.List; @b@import org.apache.log4j.Logger; @b@import com.xwood.common.util.date.DateUtils;@b@@b@/**@b@ * 类描述: 近似类(e.g. POJO vs DTO ) 存在多个同名属性,本类为从源对象生成目标对象提供便利@b@ * <br/><b><font color="red">注:目前只对同名属性进行赋值,非同名属性忽略,请自行对应</font></b>@b@ * <p>当源对象或目标对象未找到属性时,会获取直接父类的属性</p> @b@ */@b@public abstract class ObjectConvertorUtils {@b@ @b@ protected static final Logger log = Logger.getLogger(ObjectConvertorUtils.class);@b@ @b@ /**@b@ * 单对象转换(e.g.POJO<->DTO)@b@ * <br/><b>需要有get/set方法</b> @b@ * @param <T>@b@ * @param source 源对象@b@ * @param dest 目标类@b@ * @param idForce 是否强制同步非同类型的同名属性(只支持基本数据类型)@b@ * @return 目标类的一个实例@b@ */@b@ public static <T> T pojoDtoConvertor(Object source, Class<T> dest, boolean isForce) {@b@ if(source == null){@b@ return null;@b@ }@b@ @b@ try {@b@ T dto = dest.newInstance();@b@ Field[] fields = dest.getDeclaredFields();@b@ @b@ Field[] totalFields = null;@b@ @b@ //直接父类@b@ Class<?> superClass = dest.getSuperclass();@b@ if(superClass != null){@b@ Field[] superFields =superClass.getDeclaredFields();@b@ totalFields = new Field[fields.length + superFields.length];@b@ @b@ for(int j = 0; j < fields.length; j++){@b@ totalFields[j] = fields[j];@b@ }@b@ @b@ for(int i = 0; i < superFields.length; i++){@b@ totalFields[i+fields.length] = superFields[i];@b@ }@b@ }else{@b@ totalFields = fields;@b@ }@b@ @b@ if (fields != null && totalFields.length > 0) {@b@ for (Field field : totalFields) {@b@ String fieldName = field.getName();@b@ String getMethodName = "get"@b@ + fieldName.substring(0, 1).toUpperCase()@b@ + fieldName.substring(1);@b@ String setMethodName = "set"@b@ + fieldName.substring(0, 1).toUpperCase()@b@ + fieldName.substring(1);@b@ @b@ Method getMethod;@b@ try {@b@ getMethod = source.getClass().getMethod(getMethodName,@b@ new Class[] {});@b@ } catch (NoSuchMethodException e) {@b@ log.warn(" class: " + source.getClass() + " do not have Method: " + getMethodName);@b@ continue;@b@ }@b@ @b@ Method setMethod;@b@ try {@b@ setMethod = dest.getMethod(setMethodName,@b@ new Class[] { field.getType() });@b@ } catch (NoSuchMethodException e) {@b@ log.warn(" class: " + dest + " do not have Method: " + setMethodName);@b@ continue;@b@ }@b@ Object obj = getMethod.invoke(source);@b@ @b@ if(obj != null){@b@ try {@b@ Field sourceField = source.getClass().getDeclaredField(field.getName()); @b@ if(field.getType().isAssignableFrom(sourceField.getType()))@b@ setMethod.invoke(dto, new Object[] { obj });@b@ else if(isForce){@b@ //两边类型都是简单类型及其封装类或String类型时才做强制转换@b@ if ((ClassUtils.isPrimitiveOrWrapper(field.getType())@b@ || field.getType().getSimpleName().equals(@b@ "String")@b@ || field.getType().getSimpleName().equals(@b@ "BigDecimal"))@b@ &&@b@ ((ClassUtils.isPrimitiveOrWrapper(sourceField.getType())@b@ || sourceField.getType().getSimpleName().equals(@b@ "String")@b@ || field.getType().getSimpleName().equals(@b@ "BigDecimal")))){@b@ field.setAccessible(true);@b@ setValue(dto, field, obj);@b@ }@b@ } @b@ } catch (NoSuchFieldException e) {@b@ log.warn("classs: " + source.getClass() + " do not have field: " + field.getName());@b@ try {@b@ Class<?> sc = source.getClass().getSuperclass();@b@ if(sc != null){@b@ Field sourceField = sc.getDeclaredField(field.getName());@b@ if(field.getType().isAssignableFrom(sourceField.getType()))@b@ setMethod.invoke(dto, new Object[] { obj });@b@ else if(isForce){@b@ //两边类型都是简单类型及其封装类或String类型时才做强制转换@b@ if ((ClassUtils.isPrimitiveOrWrapper(field.getType())@b@ || field.getType().getSimpleName().equals(@b@ "String")@b@ || field.getType().getSimpleName().equals(@b@ "BigDecimal"))@b@ &&@b@ ((ClassUtils.isPrimitiveOrWrapper(sourceField.getType())@b@ || sourceField.getType().getSimpleName().equals(@b@ "String")@b@ || field.getType().getSimpleName().equals(@b@ "BigDecimal")))){@b@ field.setAccessible(true);@b@ setValue(dto, field, obj);@b@ }@b@ }@b@ }else{@b@ continue;@b@ }@b@ } catch (NoSuchFieldException e1) {@b@ log.warn("super classs: " + source.getClass().getSuperclass() + " do not have field: " + field.getName());@b@ continue;@b@ }@b@ }@b@ }@b@ }@b@ }@b@@b@ return dto;@b@@b@ } catch (InstantiationException e) {@b@ log.error(e.toString());@b@ } catch (SecurityException e) {@b@ log.error(e.toString());@b@ } catch (InvocationTargetException e) {@b@ log.error(e.toString());@b@ } catch (IllegalAccessException e) {@b@ log.error(e.toString());@b@ } catch (IllegalArgumentException e) {@b@ log.error(e.toString());@b@ }@b@@b@ return null;@b@ }@b@ @b@ private static void setValue(Object obj, Field field, Object value) throws IllegalAccessException{@b@ if(value == null){@b@ return;@b@ }@b@ try{@b@ field.set(obj, value);@b@ }catch(IllegalArgumentException e){@b@ field.set(obj, getRealValue(field.getType(),value));@b@ }@b@ }@b@ @b@ private static Object getRealValue(Class<?> type, Object value){@b@ if(int.class.isAssignableFrom(type)){@b@ return new Integer(value.toString());@b@ }else if(long.class.isAssignableFrom(type)){@b@ return new Long(value.toString());@b@ }else if(boolean.class.isAssignableFrom(type)){@b@ return new Boolean(value.toString());@b@ }else if(double.class.isAssignableFrom(type)){@b@ return new Double(value.toString());@b@ }else if(char.class.isAssignableFrom(type)){@b@ return (Character) value.toString().charAt(0);@b@ }else if(short.class.isAssignableFrom(type)){@b@ return new Short(value.toString());@b@ }else if(float.class.isAssignableFrom(type)){@b@ return new Float(value.toString());@b@ }else if(byte.class.isAssignableFrom(type)){@b@ return new Byte(value.toString());@b@ }else if(BigDecimal.class.isAssignableFrom(type)){@b@ return new BigDecimal(value.toString());@b@ }@b@ if(Date.class.isAssignableFrom(type)){@b@ return DateUtils.string2Date(value.toString());@b@ }@b@ return null;@b@ }@b@ @b@ /**@b@ * 集合对象转换(e.g.List<POJO> <-> List<DTO>)@b@ * <br/><b>需要有get/set方法</b> @b@ * @param <T>@b@ * @param source 源对象集合@b@ * @param dest 目标类@b@ * @param isForce 是否强制@b@ * @return@b@ */@b@ public static <T> List<T> pojoDtoCollectionConvertor(List<?> source, Class<T> dest, boolean isForce) {@b@ if(source == null){@b@ return null;@b@ }@b@ List<T> list = new ArrayList<T>();@b@ for(Object o : source){@b@ if(o == null) continue;@b@ T t = pojoDtoConvertor(o, dest, isForce);@b@ if( t != null )list.add(t);@b@ }@b@ return list;@b@ }@b@ @b@ /**@b@ * 对象转换(e.g.POJO<->DTO) @b@ * @param <T>@b@ * @param source 源对象@b@ * @param target 目标对象@b@ */@b@ public static void pojoDtoConvertor(Object source, Object target) {@b@ if(source == null || target == null){@b@ return;@b@ }@b@ Class<?> sourceClazz = source.getClass();@b@ Class<?> targetClazz = target.getClass();@b@ log.debug("---source object class type is " + sourceClazz.toString());@b@ log.debug("---target object class type is " + targetClazz.toString());@b@ Field[] fields = sourceClazz.getDeclaredFields();@b@ Field targetField;@b@ for (Field field : fields) {@b@ field.setAccessible(true);@b@ try {@b@ Object property = field.get(source);@b@ targetField = targetClazz.getDeclaredField(field.getName());@b@ if (targetField.getType().isAssignableFrom(field.getType())) {@b@ if (property != null)@b@ log.debug("---copy field " + field.getName()@b@ + ",tareget field " + targetField.toString()@b@ + ",value is " + property.toString());@b@ targetField.setAccessible(true);@b@ targetField.set(target, property);@b@ }@b@ } catch (IllegalArgumentException e) {@b@ log.error("IllegalArgument " + e);@b@ } catch (IllegalAccessException e) {@b@ log.error("Illegal Access " + e);@b@ } catch (SecurityException e) {@b@ e.printStackTrace();@b@ } catch (NoSuchFieldException e) {@b@ log.debug("---no such field[" + field.getName()@b@ + "] in target object..");@b@ continue;@b@ }@b@ }@b@ }@b@ @b@}
import java.sql.Timestamp;@b@import java.text.DateFormat;@b@import java.text.ParseException;@b@import java.text.SimpleDateFormat;@b@import java.util.ArrayList;@b@import java.util.Calendar;@b@import java.util.Date;@b@import java.util.List;@b@ @b@public class DateUtils {@b@ @b@ private final static String pattern = "yyyy-MM-dd HH:mm:ss";@b@ private final static String forPattern="yyyy-M-d";@b@ @b@ public static String dateToString(){@b@ SimpleDateFormat sdf = new SimpleDateFormat(pattern);@b@ return sdf.format(new Date());@b@ }@b@ @b@ /**@b@ * 获得月初@b@ * @param object(转出表)@b@ * @return getFirstDateOfCurMonth@b@ * @throws ParseException @b@ */@b@ public static String getFirstDateByCurDate(String date) throws ParseException{@b@ Calendar first =stringToCalendar(date);@b@ int minDay = first.getMinimum(Calendar.DAY_OF_MONTH);@b@ minDay = first.getMinimum(Calendar.DAY_OF_MONTH);@b@ first.set(Calendar.DAY_OF_MONTH, minDay);@b@ SimpleDateFormat sdf = new SimpleDateFormat(forPattern);@b@ return sdf.format(first.getTime());@b@ }@b@ @b@ public static Calendar stringToCalendar(String date) throws ParseException{@b@ Calendar calendar = Calendar.getInstance();@b@ Date firstDate = null;@b@ try {@b@ firstDate = DateUtils.stringToDate(date, forPattern);@b@ } catch (ParseException e) {@b@ e.printStackTrace();@b@ }@b@ calendar.setTime(firstDate);@b@ return calendar;@b@ }@b@ @b@ public static String dateToString(Date object){@b@ if(null==object){@b@ return null;@b@ }@b@ SimpleDateFormat sdf = new SimpleDateFormat(pattern);@b@ return sdf.format(object);@b@ @b@ }@b@ @b@ public static Date stringToDate(String date) throws ParseException{@b@ SimpleDateFormat sdf = new SimpleDateFormat(pattern);@b@ return sdf.parse(date);@b@ }@b@ @b@ public static Date stringToDate(String date,String pattern) throws ParseException{@b@ if(date == null || "".equals(date.trim())||"null".equals(date.trim())){@b@ return null;@b@ }@b@ SimpleDateFormat sdf = new SimpleDateFormat(pattern);@b@ return sdf.parse(date);@b@ }@b@ @b@ public static String getStrNowDateHmsMs(){@b@ Date tdate = new Date();@b@ String nowtime = new Timestamp(tdate.getTime()).toString();@b@ int len = nowtime.length();@b@ int between = 23-len;@b@ for(int i=0;i<between;i++){@b@ nowtime = nowtime+"0";@b@ }@b@ String nowYear = nowtime.substring(0, 4);@b@ String nowMonth = nowtime.substring(5, 7);@b@ String nowDay = nowtime.substring(8, 10);@b@ String nowHour = nowtime.substring(11, 13);@b@ String nowMinute = nowtime.substring(14, 16);@b@ String nowSecond = nowtime.substring(17, 19);@b@ String nowMilliSecond = nowtime.substring(20, 23);@b@ String nowdate = nowYear + nowMonth + nowDay + nowHour + nowMinute + nowSecond + nowMilliSecond;@b@ return nowdate;@b@ }@b@ @b@ /**@b@ * 20030801@b@ */@b@ public static String getStrNowDate() {@b@ java.util.Date tdate = new java.util.Date();@b@ String nowtime = new Timestamp(tdate.getTime()).toString();@b@ nowtime = nowtime.substring(0, 10);@b@ String nowYear = nowtime.substring(0, 4);@b@ String nowMonth = nowtime.substring(5, 7);@b@ String nowDay = nowtime.substring(8, 10);@b@ String nowdate = nowYear + nowMonth + nowDay;@b@ return nowdate;@b@@b@ }@b@ @b@ /**@b@ * 20030801@b@ */@b@ public static String getStrMonthFirstDay() {@b@ java.util.Date tdate = new java.util.Date();@b@ String nowtime = new Timestamp(tdate.getTime()).toString();@b@ nowtime = nowtime.substring(0, 10);@b@ String nowYear = nowtime.substring(0, 4);@b@ String nowMonth = nowtime.substring(5, 7);@b@ String nowDay = "01";@b@ String nowdate = nowYear + nowMonth + nowDay;@b@ return nowdate;@b@@b@ }@b@ @b@ /**@b@ * 20030801@b@ */@b@ public static String getMonthFirstDay() {@b@ java.util.Date tdate = new java.util.Date();@b@ String nowtime = new Timestamp(tdate.getTime()).toString();@b@ return nowtime.substring(0, 8)+"01";@b@@b@ }@b@ @b@ /**@b@ * 取得上个月字符串 20007@b@ */@b@ public static String getStrPreviousMonth(){@b@ Calendar cal = Calendar.getInstance(); @b@ cal.add(Calendar.MONTH, -1 );@b@ int month = cal.get(Calendar.MONTH)+1;@b@ int year = cal.get(Calendar.YEAR);@b@ String mon = String.valueOf(month);@b@ if(mon.length()<2){@b@ return year+"0"+mon;@b@ }else{@b@ return year+mon;@b@ }@b@ }@b@ @b@ /**@b@ * 取得上个月 2008-07@b@ */@b@ public static String getPreviousMonth(){@b@ Calendar cal = Calendar.getInstance(); @b@ cal.add(Calendar.MONTH, -1 );@b@ int month = cal.get(Calendar.MONTH)+1;@b@ int year = cal.get(Calendar.YEAR);@b@ String mon = String.valueOf(month);@b@ if(mon.length()<2){@b@ return year+"-0"+mon;@b@ }else{@b@ return year+"-"+mon;@b@ }@b@ }@b@ @b@ /**@b@ * 取得上个月最后一天 20050430@b@ */@b@ public static String getStrPreviousMonthDate(){@b@ Calendar cal=Calendar.getInstance();//当前日期 @b@ cal.set(Calendar.DATE,1);//设为当前月的1号 @b@ cal.add(Calendar.DATE,-1);//减一天,变为上月最后一天 @b@ SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd"); @b@ return simpleDateFormat.format(cal.getTime());//输出 @b@ }@b@ @b@ /**@b@ * 取得上个月最后一天 2005-04-30@b@ */@b@ public static String getPreviousMonthDate(){@b@ Calendar cal=Calendar.getInstance();//当前日期 @b@ cal.set(Calendar.DATE,1);//设为当前月的1号 @b@ cal.add(Calendar.DATE,-1);//减一天,变为上月最后一天 @b@ SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); @b@ return simpleDateFormat.format(cal.getTime());//输出20050430 @b@ }@b@ @b@ /**@b@ * 取得明天 2005-05-01@b@ */@b@ public static String getTomorrowDate(){@b@ Calendar cal=Calendar.getInstance();//当前日期 @b@ cal.add(Calendar.DATE,+1);//加一天 @b@ SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); @b@ return simpleDateFormat.format(cal.getTime());//输出2005-05-01 @b@ }@b@ @b@ /**@b@ * 20030801151515@b@ */@b@ public static String getStrNowDateHms() {@b@ java.util.Date tdate = new java.util.Date();@b@ String nowtime = new Timestamp(tdate.getTime()).toString();@b@ nowtime = nowtime.substring(0, 19);@b@ String nowYear = nowtime.substring(0, 4);@b@ String nowMonth = nowtime.substring(5, 7);@b@ String nowDay = nowtime.substring(8, 10);@b@ String nowHour = nowtime.substring(11, 13);@b@ String nowMinute = nowtime.substring(14, 16);@b@ String nowSecond = nowtime.substring(17, 19);@b@ String nowdate = nowYear + nowMonth + nowDay + nowHour + nowMinute + nowSecond;@b@ return nowdate;@b@ }@b@ @b@ /**@b@ * 2009-03-31@b@ */@b@ public static String getNowDate() {@b@ java.util.Date tdate = new java.util.Date();@b@ String nowtime = new Timestamp(tdate.getTime()).toString();@b@ nowtime = nowtime.substring(0, 10);@b@ return nowtime;@b@ }@b@@b@ /**@b@ * 2009-03-31 15:48:28@b@ */@b@ public static String getNowDateHms() {@b@ java.util.Date tdate = new java.util.Date();@b@ String nowtime = new Timestamp(tdate.getTime()).toString();@b@ nowtime = nowtime.substring(0, 19);@b@ return nowtime;@b@ }@b@ @b@ public static String dateToString(Date date, String pattern) {@b@ try{@b@ DateFormat format = new SimpleDateFormat(pattern); @b@ String str = format.format(date);@b@ return str;@b@ }catch(Exception e){@b@ return null;@b@ }@b@ }@b@ @b@ /**@b@ * 根据传入的日期得到上个月yyyy-mm的形式,例如传入2009-11-11,得到2009-10@b@ * @param date 传入的日期@b@ * @return 转化后的日期@b@ */@b@ public static String getPreviousMonth(String strDate){@b@ java.sql.Date date = java.sql.Date.valueOf(strDate);@b@ Calendar calendar = Calendar.getInstance();@b@ calendar.setTime(date);@b@ calendar.set(Calendar.MONTH,calendar.get(Calendar.MONTH)-1);@b@ DateFormat format = new SimpleDateFormat("yyyy-MM");@b@ return format.format(calendar.getTime());@b@ }@b@ @b@ public static String getPreviousMonthEndDay(String strDate){@b@ java.sql.Date date = java.sql.Date.valueOf(strDate);@b@ Calendar calendar = Calendar.getInstance();@b@ calendar.setTime(date);@b@ calendar.set(Calendar.DAY_OF_MONTH,1);@b@ calendar.add(Calendar.DAY_OF_YEAR, -1);@b@ DateFormat format = new SimpleDateFormat("yyyyMMdd");@b@ return format.format(calendar.getTime());@b@ }@b@ @b@ /** @b@ * 检查日期合法性 @b@ * @param s String@b@ * @param dataFormat String 日期样式,比如"yyyy-mm-dd","yyyymmddHHmmSS"@b@ * @return boolean @b@ */ @b@ public static boolean checkDate(String s, String dataFormat) {@b@ boolean ret = true;@b@ try {@b@ DateFormat df = new SimpleDateFormat(dataFormat);@b@ ret = df.format(df.parse(s)).equals(s);@b@ } catch (ParseException e) {@b@ ret = false;@b@ }@b@ return ret;@b@ }@b@ @b@ public static Date string2Date(String s){@b@ List<DateFormat> formats = new ArrayList<DateFormat>();@b@ formats.add( new SimpleDateFormat("yyyy-MM-dd") );@b@ formats.add( new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") );@b@ formats.add( new SimpleDateFormat("yy-MM-dd") );@b@ formats.add( new SimpleDateFormat("yy-MM-dd HH:mm:ss") );@b@ formats.add( new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS") );@b@ @b@ formats.add( new SimpleDateFormat("yyyy/MM/dd HH:mm:ss") );@b@ formats.add( new SimpleDateFormat("yyyy/MM/dd") );@b@ formats.add( new SimpleDateFormat("yy/MM/dd") );@b@ formats.add( new SimpleDateFormat("yy/MM/dd HH:mm:ss") );@b@ @b@ @b@ formats.add( new SimpleDateFormat("yyyyMMdd HH:mm:ss") );@b@ formats.add( new SimpleDateFormat("yyyyMMddHHmmss") );@b@ formats.add( new SimpleDateFormat("yyyyMMddHHmm") );@b@ formats.add( new SimpleDateFormat("yyyyMMddHH") );@b@ formats.add( new SimpleDateFormat("yyyyMMdd") );@b@ @b@ formats.add( new SimpleDateFormat("yyyy.MM.dd") );@b@ formats.add( new SimpleDateFormat("yyyy.MM.dd HH:mm:ss") );@b@@b@ formats.add( new SimpleDateFormat("EEE MMM d hh:mm:ss a z yyyy") );@b@ formats.add( new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy") );@b@ @b@ for(DateFormat format:formats){@b@ try {@b@ Date d = format.parse(s);@b@ return d;@b@ } catch (ParseException e) {@b@ }@b@ }@b@ return null;@b@ }@b@ @b@ @b@ /** @b@ * 获得当年1月1日的日期 @b@ */@b@ public static String getFirstDayOfYear(String str) {@b@ SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");@b@ Date date = null;@b@ String year = null;@b@ try {@b@ date = sd.parse(str);@b@ Calendar calendar = Calendar.getInstance();@b@ calendar.setTime(date);@b@ SimpleDateFormat sdf = new SimpleDateFormat("yyyy");@b@ year = sdf.format(calendar.getTime());@b@ return year + "-01-01 00:00:00";@b@ } catch (ParseException e) {@b@ e.printStackTrace();@b@ }@b@ return year;@b@ }@b@ @b@ /**@b@ * 判断时间是否在凌晨19:00:00 ~~23:59:59@b@ */@b@ public static boolean is7To12(){@b@ Calendar cal = Calendar.getInstance();@b@ SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");@b@ String c = sdf.format(cal.getTime());@b@ Integer time = Integer.parseInt(c.replace(":",""));@b@ if(time>=190000 && time <=235959){@b@ return true;@b@ }@b@ return false;@b@ }@b@ @b@ /**@b@ * 判断时间是否在凌晨00:00:00 ~~05:00:00@b@ */@b@ public static boolean is0To5(){@b@ Calendar cal = Calendar.getInstance();@b@ SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");@b@ String c = sdf.format(cal.getTime());@b@ Integer time = Integer.parseInt(c.replace(":",""));@b@ if(time>=1 && time <=50000){@b@ return true;@b@ }@b@ return false;@b@ }@b@ @b@ /**@b@ * 根据传入日期param参数获取前一天日期@b@ * @param param: yyyy-MM-dd HH:mm:ss@b@ */@b@ public static String getYesterDay(String param){@b@ SimpleDateFormat frt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");@b@ try {@b@ Date date = frt.parse(param);@b@ Calendar cal = Calendar.getInstance();@b@ cal.setTime(date);@b@ cal.add(Calendar.DATE, -1);@b@ return frt.format(cal.getTime());@b@ } catch (ParseException e) {@b@ e.printStackTrace();@b@ }catch(Exception e){@b@ e.printStackTrace();@b@ }@b@ return null;@b@ }@b@ @b@ /**@b@ * 根据传入日期param参数获取35天前的日期@b@ * @param param: yyyy-MM-dd HH:mm:ss@b@ **/@b@ public static String getBefore35(String param){@b@ SimpleDateFormat frt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");@b@ try {@b@ Date date = frt.parse(param);@b@ Calendar cal = Calendar.getInstance();@b@ cal.setTime(date);@b@ cal.add(Calendar.DATE, -34);@b@ return frt.format(cal.getTime());@b@ } catch (ParseException e) {@b@ e.printStackTrace();@b@ }catch(Exception e){@b@ e.printStackTrace();@b@ }@b@ return null;@b@ }@b@ @b@ /** @b@ * 判断当前日期是否是一周的第一天 @b@ */@b@ public static boolean isFirstDayOfWeek() {@b@ Calendar cal = Calendar.getInstance();@b@ cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);// 这里设置从周一开始,若需要根据系统时区自动获取,则采用下边的方式@b@ Calendar cal2 = Calendar.getInstance();@b@ return cal.equals(cal2);@b@ }@b@@b@ /** @b@ * 判断当前日期是否是一月的第一天 @b@ */@b@ public static boolean isFirstDayOfMonth() {@b@ Calendar cal = Calendar.getInstance();@b@ cal.set(Calendar.DAY_OF_MONTH, 1);// 这里设置从周一开始,若需要根据系统时区自动获取,则采用下边的方式@b@ Calendar cal2 = Calendar.getInstance();@b@ return cal.equals(cal2);@b@ }@b@@b@ /**@b@ * 当前日期的获得本月1号日期 calendar 当前日期@b@ */@b@ public static String getFirstDateOfCurMonth(Calendar calendar) {@b@ Calendar first = Calendar.getInstance();@b@ first.setTime(calendar.getTime());@b@@b@ int minDay = first.getMinimum(Calendar.DAY_OF_MONTH);@b@@b@ minDay = first.getMinimum(Calendar.DAY_OF_MONTH);@b@ first.set(Calendar.DAY_OF_MONTH, minDay);@b@ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");@b@ return sdf.format(first.getTime());@b@ }@b@@b@ /** @b@ * 获得上个月1号 @b@ */@b@ public static Date getFirstDateOfLastMonth(Calendar calendar) {@b@ Calendar first = Calendar.getInstance();@b@ first.setTime(calendar.getTime());@b@@b@ int minDay = first.getMinimum(Calendar.DAY_OF_MONTH);@b@ first.add(Calendar.MONTH, -1);@b@@b@ minDay = first.getMinimum(Calendar.DAY_OF_MONTH);@b@ first.set(Calendar.DAY_OF_MONTH, minDay);@b@ return first.getTime();@b@ }@b@@b@ /** @b@ * 获取上个月最后一天的日期 @b@ */@b@ public static Date getLastDateOfLastMonth(Calendar calendar) {@b@ Calendar last = Calendar.getInstance();@b@ last.setTime(calendar.getTime());@b@@b@ int maxDay = last.getMaximum(Calendar.DAY_OF_MONTH);@b@ last.add(Calendar.MONTH, -1);@b@@b@ maxDay = last.getActualMaximum(Calendar.DAY_OF_MONTH);@b@ last.set(Calendar.DAY_OF_MONTH, maxDay);@b@ return last.getTime();@b@ }@b@@b@ /**@b@ * 获取日期所在月的最后一天的日期@b@ * @param calendar@b@ * @return@b@ */@b@ public static Date getLastDateOfMonth(Date date)@b@ {@b@ Calendar last = Calendar.getInstance();@b@ last.setTime(date);@b@ @b@ int maxDay = last.getActualMaximum(Calendar.DAY_OF_MONTH);@b@ last.set(Calendar.DAY_OF_MONTH, maxDay);@b@ return last.getTime();@b@ @b@ }@b@ @b@ @b@ public static String getDateYMD(Date date)@b@ {@b@ Calendar c = Calendar.getInstance();@b@ c.setTime(date);@b@ String ymd = c.get(Calendar.YEAR)+""+c.get(Calendar.MONTH)+""+c.get(Calendar.DATE);@b@ return ymd;@b@ }@b@ /** @b@ * 获得上周第一天的日期 @b@ */@b@ public static Date getFirstDateOfLastWeek(Calendar calendar) {@b@ Calendar first = Calendar.getInstance();@b@ first.setTime(calendar.getTime());@b@ first.setFirstDayOfWeek(Calendar.MONDAY);@b@ int index = first.getFirstDayOfWeek();@b@ first.set(Calendar.DAY_OF_WEEK, index);@b@ first.add(Calendar.DAY_OF_WEEK, -7);@b@ return first.getTime();@b@ }@b@@b@ /** @b@ * 获得上周最后一天的日期 @b@ */@b@ public static Date getLastDateOfLastWeek(Calendar calendar) {@b@ Calendar last = Calendar.getInstance();@b@ last.setTime(calendar.getTime());@b@ last.setFirstDayOfWeek(Calendar.MONDAY);@b@ int index = last.getFirstDayOfWeek();@b@ last.set(Calendar.DAY_OF_WEEK, index);@b@ last.add(Calendar.DAY_OF_WEEK, -1);@b@ return last.getTime();@b@ }@b@@b@ /** @b@ * 获得日期date所在的当前周数@b@ */@b@ public static String getConvertoWeekDate(String date, String inputFormat)@b@ throws ParseException {@b@ SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");@b@ Date myd = format.parse(date);@b@ SimpleDateFormat sdf = new SimpleDateFormat(inputFormat);@b@ Calendar ccc = Calendar.getInstance();@b@ ccc.setTime(myd);@b@ ccc.setFirstDayOfWeek(Calendar.MONDAY);@b@@b@ /**/@b@ String str = date.substring(0, 4);@b@ SimpleDateFormat tempFormat = new SimpleDateFormat("yyyy-MM-dd");@b@ Date compara = tempFormat.parse(str + "-01-01");@b@ Calendar CalP = Calendar.getInstance();@b@ CalP.setTime(compara);@b@ int x = CalP.get(Calendar.DAY_OF_WEEK);@b@ /**/@b@ if (x != 2) {@b@ sdf.setCalendar(ccc);@b@ String s = sdf.format(ccc.getTime());@b@ String s1 = s.substring(0, 4);@b@ String s2 = s.substring(4, 6);@b@ Integer i = Integer.parseInt(s2);@b@ if (i > 1) {@b@ i = i - 1;@b@ }@b@ s2 = i + "";@b@ if ((i + "").length() < 2) {@b@ s2 = "0" + i;@b@ }@b@ return s1 + s2;@b@ } else {@b@ sdf.setCalendar(ccc);@b@ return sdf.format(ccc.getTime());@b@ }@b@ }@b@@b@ /**@b@ * 获得前一天开始的日期 @b@ */@b@ public static String getYesterdayStart(Calendar calendar) {@b@ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");@b@ Calendar cal = Calendar.getInstance();@b@ cal.setTime(calendar.getTime());@b@ cal.add(Calendar.DATE, -1);@b@ return sdf.format(cal.getTime()) + " 00:00:00";@b@ }@b@@b@ /** @b@ * 获得前一天结束的日期 @b@ */@b@ public static String getYesterdayEnd(Calendar calendar) {@b@ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");@b@ Calendar cal = Calendar.getInstance();@b@ cal.setTime(calendar.getTime());@b@ cal.add(Calendar.DATE, -1);@b@ return sdf.format(cal.getTime()) + " 23:59:59";@b@ }@b@@b@ /** @b@ * 获得前一天的日期 @b@ */@b@ public static String getYesterday(Calendar calendar) {@b@ SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");@b@ Calendar cal = Calendar.getInstance();@b@ cal.setTime(calendar.getTime());@b@ cal.add(Calendar.DATE, -1);@b@ return sdf.format(cal.getTime());@b@ }@b@@b@ public static Date StringToDate(String date) throws ParseException {@b@ SimpleDateFormat sdf = new SimpleDateFormat();@b@ sdf.applyPattern("yyyy-MM-dd HH:mm:ss");@b@ return sdf.parse(date);@b@ }@b@@b@ public static Date StringToDate(String date, String pattern)@b@ throws ParseException {@b@ if (date == null || "".equals(date.trim())@b@ || "null".equals(date.trim())) {@b@ return null;@b@ }@b@ SimpleDateFormat sdf = new SimpleDateFormat();@b@ sdf.applyPattern(pattern);@b@ return sdf.parse(date);@b@ }@b@ @b@ public static String getOracleDate()@b@ {@b@ String str ="to_date('"+DateUtils.dateToString()+"','YYYY-MM-DD HH24:MI:SS')";@b@ return str;@b@ }@b@ /** @b@ * 月份范围-上月的26号到本月的25号 @b@ * 例:201208 2012-07-26~2012-08-25@b@ * @param operDate yyyy-MM-dd@b@ * @param month_flag yyyyMMdd@b@ * @return@b@ * @throws ParseException @b@ */@b@ public static boolean tskfContainDate(String operDate,String month_flag) {@b@ try{@b@ String endDateStr=month_flag+"25";@b@ Date tarDate=stringToDate(operDate, "yyyy-MM-dd");@b@ Date endDate=stringToDate(endDateStr, "yyyyMMdd");@b@ Calendar calendar=Calendar.getInstance();@b@ calendar.setTime(endDate);@b@ calendar.add(Calendar.MONTH, -1);@b@ calendar.add(Calendar.DAY_OF_MONTH, 1);@b@ Date firstDate=calendar.getTime();@b@ if(tarDate.compareTo(firstDate)<0||tarDate.compareTo(endDate)>0){@b@ return false;@b@ }@b@ }catch (ParseException e){@b@ e.printStackTrace();@b@ }@b@ @b@ return true;@b@ }@b@ @b@ /** @b@ * 月份范围-本月的26号到下月的25号 @b@ * 例:201208 2012-08-26~2012-09-25@b@ * @param operDate yyyy-MM-dd@b@ * @param month_flag yyyyMMdd@b@ * @return@b@ * @throws ParseException @b@ */@b@ public static boolean tskfMonthDate(String month_flag) {@b@ try{@b@ String firstDateStr=month_flag+"26";@b@ Date firstDate=stringToDate(firstDateStr, "yyyyMMdd");@b@ Calendar calendar=Calendar.getInstance();@b@ calendar.setTime(firstDate);@b@ calendar.add(Calendar.MONTH, 1);@b@ Date endDate=calendar.getTime();@b@ Date tarDate=new Date();@b@ if(tarDate.compareTo(firstDate)<0||tarDate.compareTo(endDate)>=0){@b@ return false;@b@ }@b@ }catch (ParseException e){@b@ e.printStackTrace();@b@ }@b@ @b@ return true;@b@ }@b@ @b@ public static void main(String[] args) throws ParseException {@b@ @b@ System.out.println(dateToString(string2Date("20140210110133"))); @b@ @b@ }@b@}