package java; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.PrintStream; import java.lang.reflect.Method; import java.math.BigDecimal; import java.net.MalformedURLException; import java.net.URL; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Stack; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.paic.pafa.app.lwc.core.util.DevLog; import com.paic.pafa.app.lwc.core.util.StringUtils; public class CommonFunctions { private static final Log logger = LogFactory.getLog(CommonFunctions.class); private CommonFunctions() { } private static final Map certificateTypeMap = new HashMap(); private static final Map caseMap = new HashMap(); static { certificateTypeMap.put("01", "1"); certificateTypeMap.put("02", "2"); certificateTypeMap.put("03", "3"); certificateTypeMap.put("05", "7"); certificateTypeMap.put("06", "6"); certificateTypeMap.put("99", "0"); caseMap.put("A", "0"); caseMap.put("B", "(0,1000]"); caseMap.put("C", "(1000,3000]"); caseMap.put("D", "(3000,5000]"); caseMap.put("E", "(5000,10000]"); caseMap.put("F", "(10000,50000]"); caseMap.put("G", "(50000,+∞)"); } private static final List PREDEFINED_CLASS_LIST = Arrays .asList(new Class[] { Date.class, String.class, Boolean.class, Class.class, Float.class, Integer.class, Double.class, Long.class }); private static final List DEFAULT_IGNORE_PROPERTY_NAME = Arrays .asList(new String[] { "class" }); public static final String EMPTY_STRING = ""; public static final NumberFormat DEFAULT_NUMBER_FORMAT = new DecimalFormat( "#.##"); public static final NumberFormat NUMBER_FORMAT_00_00 = new DecimalFormat( "0.##"); public static final NumberFormat NUMBER_FORMAT_00_00_ZERO_PRESENT = new DecimalFormat( "0.00"); public static final NumberFormat NUMBER_FORMAT_00_0000 = new DecimalFormat( "0.####"); private static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd"; public static final String DATE_FORMAT_YYYY = "yyyy"; public static final String DATE_FORMAT_MM = "MM"; public static final String DATE_FORMAT_DD = "dd"; public static final String DATE_FORMAT_YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss"; public static final String DATE_FORMAT_YYYY_MM_DD = DEFAULT_DATE_FORMAT; public static final String DATE_FORMAT_YYYY_MM_DD_NO_SEPATOR = "yyyyMMdd"; private static final String[] NUM_NAMES = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" }; private static final String[] DIGITAL_NAMES = { "", "", "拾", "佰", "仟", "万", "拾" }; private static String convertForInteger(String num) throws Exception { if (Integer.parseInt(num) == 0) return ""; char[] list = num.toCharArray(); Stack stack = new Stack(); boolean _continual = false; for (int i = 1; i < list.length + 1; i++) { int pos = list.length - i; int _v = Integer.parseInt(String.valueOf(list[pos])); if (_v == 0) { if (!_continual) { _continual = true; } } else { if (_continual) { stack.push("零"); _continual = false; } stack.push(DIGITAL_NAMES[i]); stack.push(NUM_NAMES[_v]); } } StringBuffer sb = new StringBuffer(); while (!stack.empty()) { sb.append((String) stack.pop()); } String value = sb.toString(); if (value.endsWith("零")) { value = value.substring(0, value.length() - 1); } return value + "元"; } private static String convertForFraction(String num) throws Exception { if (num.length() < 2) { num = num + "0"; } char[] list = num.toCharArray(); int _v1 = Integer.parseInt(String.valueOf(list[0])); int _v2 = Integer.parseInt(String.valueOf(list[1])); if (_v1 == 0 && _v2 == 0) { return ""; } else { String value = ""; if (_v1 != 0) { value = value + NUM_NAMES[_v1] + "角"; } if (_v2 != 0) { value = value + NUM_NAMES[_v2] + "分"; } return value; } } /** * 数字转换成中文表示. 如1500->壹仟伍佰元 * * @param num * @return * @throws Exception */ public static String convertNumberToChinese(String num) throws Exception { int pos = num.indexOf("."); String result = ""; if (pos > -1) { String value1 = convertForInteger(num.substring(0, pos)); String value2 = convertForFraction(num.substring(pos + 1)); if (!StringUtils.hasText(value2)) { value2 = "整"; } result = value1 + value2; } else { result = convertForInteger(num) + "整"; } if ("整".equals(result)) { return "零元整"; } return result; } /** * 把bean转换成Map. 目前有点问题,不要调用 * * @param bean * @return */ public static Map beanToMap(Object bean) { if (null == bean) return new HashMap(0); Map m = new HashMap(); try { BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo .getPropertyDescriptors(); for (int i = 0; i < propertyDescriptors.length; i++) { Object value = propertyDescriptors[i].getReadMethod().invoke( bean, null); if (DEFAULT_IGNORE_PROPERTY_NAME .contains(propertyDescriptors[i].getName())) { continue; } else if (value == null) { m.put(propertyDescriptors[i].getName(), null); } else if (PREDEFINED_CLASS_LIST.contains(value.getClass())) { m.put(propertyDescriptors[i].getName(), value); } else if (value instanceof List) { List l = (List) value; List convertedList = new ArrayList(l.size()); for (Iterator iter = l.iterator(); iter.hasNext();) { Object element = (Object) iter.next(); if (element == null) { convertedList.add(null); } else if (PREDEFINED_CLASS_LIST.contains(element .getClass())) { convertedList.add(element); } else { convertedList.add(beanToMap(element)); } } m.put(propertyDescriptors[i].getName(), convertedList); } else { m.put(propertyDescriptors[i].getName(), beanToMap(value)); } } } catch (Exception e) { e.printStackTrace(System.err); return new HashMap(0); } return m; } private static final String NULL_STRING = "null"; /** * 以className[field1=value1,field2=value2,...]的形式返回bean的字符串表示 * * @param bean * @return */ public static String introspectBean(Object bean) { return introspectBean(bean, null); } /** * 以className[field1=value1,field2=value2,...]的形式返回bean的字符串表示 * * @param bean * @param ignorePropertyNames * 忽略的属性名称. 若传入null则返回所有属性 * @return */ public static String introspectBean(Object bean, String[] ignorePropertyNames) { if (null == bean) { return NULL_STRING; } StringBuffer sb = new StringBuffer(); List ignorePropertyNameList = new ArrayList(0); if (null != ignorePropertyNames && ignorePropertyNames.length > 0) { ignorePropertyNameList = Arrays.asList(ignorePropertyNames); } sb.append(bean.getClass().getName()); sb.append(‘[‘); sb.append(‘\n‘); try { BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo .getPropertyDescriptors(); for (int i = 0; i < propertyDescriptors.length; i++) { String propertyName = propertyDescriptors[i].getName(); if (ignorePropertyNameList.contains(propertyName)) { continue; } Object propertyValue = propertyDescriptors[i].getReadMethod() .invoke(bean, null); sb.append(‘\t‘); sb.append(propertyName); sb.append(‘=‘); sb.append(propertyValue); sb.append(‘,‘); sb.append(‘\n‘); } } catch (Exception e) { return bean.getClass().getName() + ".toString() failed with exception:" + e.getMessage(); } sb.append(‘]‘); return sb.toString(); } /** * 字符串的空值处理 */ public static boolean isEmpty(String str) { if ((str == null) || (str.equals("null"))) { return true; } else { return false; } } /** * 字符串的空值处理 */ public static String changeNullStringToEmpty(String str) { if ((str == null) || (str.equals("null"))) { return ""; } else { return str.trim(); } } /** * 对象toString的空值处理 */ public static String changeNullStringToEmpty(Object obj) { if (obj == null) { return ""; } else { return obj.toString(); } } /** * 将空字符串变为指定的值 add by zhaopu */ public static String changeNullStringToValue(String str, String Value) { if (str == null) { return Value; } else { return str.trim(); } } /** * 将空字符和null串变为指定的值 add by wanghl 2003-10-23 */ public static String changeEmptyStringToValue(String str, String Value) { if (str == null || "".equals(str.trim())) { return Value; } else { return str.trim(); } } /** * 将datetime类型的时间转化成字符串 YYYY-MM-DD */ public static String changeDateFormat(java.sql.Date dateTime) { if (dateTime == null) { return ""; } else { Calendar calen = Calendar.getInstance(); calen.setTime(dateTime); String year = new Integer(calen.get(Calendar.YEAR)).toString(); String month = new Integer(calen.get(Calendar.MONTH) + 1) .toString(); if (month.length() < 2) { month = "0" + month; } String date = new Integer(calen.get(Calendar.DATE)).toString(); if (date.length() < 2) { date = "0" + date; } return year + "-" + month + "-" + date; } } /** * 将datetime类型的时间转化成字符串 YYYY-MM-DD HH:MI:SS */ public static String changeDateTimeFormat(java.sql.Date dateTime) { if (dateTime == null) { return ""; } else { Calendar calen = Calendar.getInstance(); calen.setTime(dateTime); String year = new Integer(calen.get(Calendar.YEAR)).toString(); String month = new Integer(calen.get(Calendar.MONTH) + 1) .toString(); if (month.length() < 2) { month = "0" + month; } String date = new Integer(calen.get(Calendar.DATE)).toString(); if (date.length() < 2) { date = "0" + date; } String hour = new Integer(calen.get(Calendar.HOUR_OF_DAY)) .toString(); if (hour.length() < 2) { hour = "0" + hour; } String minute = new Integer(calen.get(Calendar.MINUTE)).toString(); if (minute.length() < 2) { minute = "0" + minute; } return year + "-" + month + "-" + date + " " + hour + ":" + minute; } } public static List split(String str1, String str2) { List ret = new ArrayList(); if (str1 == null || str1.equals("")) return ret; while (str1.indexOf(str2) >= 0) { String temp = str1.substring(0, str1.indexOf(str2)); str1 = str1.substring(str1.indexOf(str2) + str2.length()); ret.add(temp); } ret.add(str1); return ret; } /** * 分割字符串 * * @param source * 源字符串 * @param separator * 分隔符 * @return 分割后的字符串 */ public static String[] splitString(String source, String separator) { if (!StringUtils.hasText(source)) { return new String[0]; } StringTokenizer st = new StringTokenizer(source, separator); String[] result = new String[st.countTokens()]; for (int i = 0; st.hasMoreTokens();) { result[i++] = st.nextToken(); } return result; } /** * 转换日期格式 */ public static String formatDateString(String dateTime, String inputFormat, String outputFormat) { try { if (dateTime == null || dateTime.equals("")) { return ""; } java.text.SimpleDateFormat iFormat = new java.text.SimpleDateFormat( inputFormat); java.util.Date iDate = iFormat.parse(dateTime); java.text.SimpleDateFormat oFormat = new java.text.SimpleDateFormat( outputFormat); String sRet = oFormat.format(iDate); return sRet; } catch (Exception e) { return ""; } } /** * 转换平台日期 * * @param circDate * yyyyMMddHHmm or yyyyMMdd * @return */ public static String formatCircDate(String circDate) { if (!StringUtils.hasText(circDate)) { return ""; } if (12 == circDate.length()) { String year = circDate.substring(0, 4); String month = circDate.substring(4, 6); String day = circDate.substring(6, 8); String hour = circDate.substring(8, 10); String minute = circDate.substring(10, 12); StringBuffer sb = new StringBuffer(25).append(year).append("年") .append(month).append("月").append(day).append("日") .append(hour).append(":").append(minute); return sb.toString(); } else if (8 == circDate.length()) { String year = circDate.substring(0, 4); String month = circDate.substring(4, 6); String day = circDate.substring(6, 8); StringBuffer sb = new StringBuffer(25).append(year).append("年") .append(month).append("月").append(day).append("日"); return sb.toString(); } return ""; } /** * 取两个日期间隔的工作日数 * * @param fromDate * @param toDate * @return */ public static int getDays(String fromDate, String toDate) { int elapsed = 0; if (fromDate == null || fromDate.equals("") || toDate == null || toDate.equals("")) { return 0; } GregorianCalendar gc1, gc2; try { int tempYear1 = Integer.parseInt(fromDate.substring(0, 4)); int tempMonth1 = Integer.parseInt(fromDate.substring(5, 7)); int tempDay1 = Integer.parseInt(fromDate.substring(8, 10)); int tempYear2 = Integer.parseInt(toDate.substring(0, 4)); int tempMonth2 = Integer.parseInt(toDate.substring(5, 7)); int tempDay2 = Integer.parseInt(toDate.substring(8, 10)); GregorianCalendar g1 = new GregorianCalendar(tempYear1, tempMonth1 - 1, tempDay1); GregorianCalendar g2 = new GregorianCalendar(tempYear2, tempMonth2 - 1, tempDay2); if (g2.after(g1)) { gc2 = (GregorianCalendar) g2.clone(); gc1 = (GregorianCalendar) g1.clone(); } else { gc2 = (GregorianCalendar) g1.clone(); gc1 = (GregorianCalendar) g2.clone(); } gc1.clear(Calendar.MILLISECOND); gc1.clear(Calendar.SECOND); gc1.clear(Calendar.MINUTE); gc1.clear(Calendar.HOUR_OF_DAY); gc2.clear(Calendar.MILLISECOND); gc2.clear(Calendar.SECOND); gc2.clear(Calendar.MINUTE); gc2.clear(Calendar.HOUR_OF_DAY); while (gc1.before(gc2)) { gc1.add(Calendar.DATE, 1); elapsed++; } return elapsed; } catch (Exception e) { return 0; } } /** * 转换页面显示格式 */ public static String changeShowFormat(String str) { return (str.equals("") ? " " : str); } public static String getGBCode(String str) { String temp = null; try { String temp_p = str; byte[] temp_t = temp_p.getBytes("ISO8859-1"); temp = new String(temp_t); } catch (Exception e) { // System.out.println("错误:"+e.getMessage()); } return temp; /* * finally { return str; } */ } /** * 实例化当前系统时间 */ private static Calendar getCalendar() { return Calendar.getInstance(); } /** * 取得当前年 */ public static String getYear() { return new Integer(getCalendar().get(Calendar.YEAR)).toString(); } /** * 取得当前月 */ public static String getMonth() { String month = new Integer(getCalendar().get(Calendar.MONTH) + 1) .toString(); if (month.length() < 2) { month = "0" + month; } return month; } /** * 取得当前日 */ public static String getDate() { String date = new Integer(getCalendar().get(Calendar.DATE)).toString(); if (date.length() < 2) { date = "0" + date; } return date; } /** * 取得当前小时 */ public static String getHour() { String hour = new Integer(getCalendar().get(Calendar.HOUR)).toString(); if (hour.length() < 2) { hour = "0" + hour; } return hour; } /** * 取得当前分钟 */ public static String getMinute() { String min = new Integer(getCalendar().get(Calendar.MINUTE)).toString(); if (min.length() < 2) { min = "0" + min; } return min; } /** * 取得当前日期 * * @return 形如yyyy-mm-dd格式的日期 */ public static String getCurrentDate() { java.util.Date curDate = new java.util.Date(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); return df.format(curDate); } /** * 取得当前时间(包括小时分) * * @return 形如yyyy-mm-dd HH:mm格式的日期 */ public static String getCurrentDateTime() { java.util.Date curDate = new java.util.Date(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm"); return df.format(curDate); } /** * 返回系统日期的后N天 * * @para days为正数表示当前日期的后N天 days为负数表示当前日期的前N天 * @return 形如yyyy-mm-dd格式的日期 */ public static String getNextDays(int days) { Calendar cld = Calendar.getInstance(); cld.add(Calendar.DATE, days); String yy = new Integer(cld.get(Calendar.YEAR)).toString(); String mm = new Integer(cld.get(Calendar.MONTH) + 1).toString(); String dd = new Integer(cld.get(Calendar.DATE)).toString(); if (mm.length() < 2) { mm = "0" + mm; } if (dd.length() < 2) { dd = "0" + dd; } return yy + "-" + mm + "-" + dd; } /** * 返回日期strDate的后N天 * * @para days为正数表示当前日期的后N天 days为负数表示当前日期的前N天 * @return 形如yyyy-mm-dd格式的日期 */ public static String getNextDays(String strDate, int days) { if (strDate == null || strDate.length() < 10) { return ""; } int year = Integer.parseInt(strDate.substring(0, 4)); int month = Integer.parseInt(strDate.substring(5, 7)); int day = Integer.parseInt(strDate.substring(8, 10)); Calendar cld = Calendar.getInstance(); cld.set(year, month - 1, day); cld.add(Calendar.DATE, days); String yy = new Integer(cld.get(Calendar.YEAR)).toString(); String mm = new Integer(cld.get(Calendar.MONTH) + 1).toString(); String dd = new Integer(cld.get(Calendar.DATE)).toString(); if (mm.length() < 2) { mm = "0" + mm; } if (dd.length() < 2) { dd = "0" + dd; } return yy + "-" + mm + "-" + dd; } private static final Calendar CAL1 = Calendar.getInstance(); private static final Calendar CAL2 = Calendar.getInstance(); public static synchronized boolean dateInTerm(Date begin, Date end, Date target) { CAL1.setTime(begin); CAL1.set(Calendar.HOUR, 0); CAL1.set(Calendar.MINUTE, 0); CAL1.set(Calendar.SECOND, 0); CAL2.setTime(end); CAL2.set(Calendar.HOUR, 23); CAL2.set(Calendar.MINUTE, 59); CAL2.set(Calendar.SECOND, 59); long targetTimeInMills = target.getTime(); DevLog.trace("CommonFunctions.dateInTerm start..."); DevLog.debug("polyBegin date:" + CAL1.getTime()); DevLog.debug("polyEnd date:" + CAL2.getTime()); DevLog.debug("target date:" + target); DevLog.debug("return value:" + (CAL1.getTimeInMillis() <= targetTimeInMills && targetTimeInMills <= CAL2 .getTimeInMillis())); DevLog.trace("CommonFunctions.dateInTerm end."); return CAL1.getTimeInMillis() <= targetTimeInMills && targetTimeInMills <= CAL2.getTimeInMillis(); } /** * 返回系统日期的后x年,y月,z天 * * @para 为正数表示当前日期向后 为负数表示当前日期向前 * @return 形如yyyy-mm-dd格式的日期 */ // add by zhaopu public static String getNextYearMonthDays(int years, int months, int days) { Calendar cld = Calendar.getInstance(); cld.add(Calendar.YEAR, years); cld.add(Calendar.MONTH, months); cld.add(Calendar.DATE, days); String yy = new Integer(cld.get(Calendar.YEAR)).toString(); String mm = new Integer(cld.get(Calendar.MONTH) + 1).toString(); String dd = new Integer(cld.get(Calendar.DATE)).toString(); if (mm.length() < 2) { mm = "0" + mm; } if (dd.length() < 2) { dd = "0" + dd; } return yy + "-" + mm + "-" + dd; } /** * 返回指定日期的后x年,y月,z天 * * @para 为正数表示当前日期向后 为负数表示当前日期向前 * @return 形如yyyy-mm-dd格式的日期 */ // add by wq public static String getNextYearMonthDays(String strDate, int years, int months, int days) { if (strDate == null || strDate.length() < 10) { return ""; } int year = Integer.parseInt(strDate.substring(0, 4)); int month = Integer.parseInt(strDate.substring(5, 7)) - 1; int day = Integer.parseInt(strDate.substring(8, 10)); Calendar cld = Calendar.getInstance(); ; cld.set(year, month, day); cld.add(Calendar.YEAR, years); cld.add(Calendar.MONTH, months); cld.add(Calendar.DATE, days); String yy = new Integer(cld.get(Calendar.YEAR)).toString(); String mm = new Integer(cld.get(Calendar.MONTH) + 1).toString(); String dd = new Integer(cld.get(Calendar.DATE)).toString(); if (mm.length() < 2) { mm = "0" + mm; } if (dd.length() < 2) { dd = "0" + dd; } return yy + "-" + mm + "-" + dd; } /** * 比较两日期大小,日期1大于等于日期2 返回1,小于返回-1,等于返回0 */ public static int compareDate(String date1, String date2) { int year1 = Integer.parseInt(date1.substring(0, 4)); int month1 = Integer.parseInt(date1.substring(5, 7)); int day1 = Integer.parseInt(date1.substring(8, 10)); int year2 = Integer.parseInt(date2.substring(0, 4)); int month2 = Integer.parseInt(date2.substring(5, 7)); int day2 = Integer.parseInt(date2.substring(8, 10)); if (year1 > year2) { return 1; } else if (year1 < year2) { return -1; } else if (year1 == year2) { if (month1 > month2) { return 1; } else if (month1 < month2) { return -1; } else if (month1 == month2) { if (day1 > day2) { return 1; } else if (day1 < day2) { return -1; } else { return 0; } } } return -2; } /** * 日期转换,由字符串转换成java.sql.Date */ public static java.sql.Date getDateFormat(String value) { long templ = 0; if (value == null) { return null; } if (value.equals("")) { return null; } else if (value.length() == 10) { int tempYear = Integer.parseInt(value.substring(0, 4)); int tempMonth = Integer.parseInt(value.substring(5, 7)); int tempDay = Integer.parseInt(value.substring(8, 10)); Calendar calen = Calendar.getInstance(); calen.set(tempYear, tempMonth - 1, tempDay); templ = calen.getTime().getTime(); } else if (value.length() == 7) { int tempYear = Integer.parseInt(value.substring(0, 4)); int tempMonth = Integer.parseInt(value.substring(5, 7)); Calendar calen = Calendar.getInstance(); calen.set(tempYear, tempMonth - 1, 1); templ = calen.getTime().getTime(); } return new java.sql.Date(templ); } /** * 日期转换,由字符串转换成java.sql.Date */ public static java.sql.Date getTimeFormat(String value) { if (value == null) { return null; } if (value.equals("")) { return null; } else { int tempYear = Integer.parseInt(value.substring(0, 4)); int tempMonth = Integer.parseInt(value.substring(5, 7)); int tempDay = Integer.parseInt(value.substring(8, 10)); int tempHour = Integer.parseInt(value.substring(11, 13)); int tempMin = Integer.parseInt(value.substring(14, 16)); int tempSec = Integer.parseInt(value.substring(17, 19)); Calendar calen = Calendar.getInstance(); calen.set(tempYear, tempMonth, tempDay, tempHour, tempMin, tempSec); return new java.sql.Date(calen.getTime().getTime()); } } public static Date parseDate(String dateString, String pattern) { DateFormat df = pattern == null ? new SimpleDateFormat( DEFAULT_DATE_FORMAT) : new SimpleDateFormat(pattern); try { return df.parse(dateString); } catch (ParseException e) { throw new IllegalArgumentException("不能解析时间:" + dateString); } } public static Date parseDate(String dateString) { try { return new SimpleDateFormat(DEFAULT_DATE_FORMAT).parse(dateString); } catch (ParseException e) { throw new IllegalArgumentException("不能解析时间:" + dateString); } } public static Date parseYear(String dateString) { try { return new SimpleDateFormat(DATE_FORMAT_YYYY).parse(dateString); } catch (ParseException e) { throw new IllegalArgumentException("不能解析时间:" + dateString); } } // add by zhaopu 将日期转换为指定的格式 public static String formatDate(Date date, String pattern) { if (date == null) { return ""; } DateFormat df = pattern == null ? new SimpleDateFormat( DEFAULT_DATE_FORMAT) : new SimpleDateFormat(pattern); return df.format(date); } public static String formatDate(Date d) { return formatDate(d, null); } public static HashMap ConvertNullHashMap(Collection attributes) { HashMap returnHashMap = new HashMap(); Iterator iterator = attributes.iterator(); String tempStr = ""; while (iterator.hasNext()) { String attributeName = (String) iterator.next(); returnHashMap.put(attributeName, tempStr); } // System.out.println("转换hashmap:" + returnHashMap); return returnHashMap; } public static boolean invokeSetMethod(String property, String value, Object bean) { // 设置运行的方法名称 String targetMethod = "set" + property.substring(0, 1).toUpperCase() + property.substring(1, property.length()); if (targetMethod == null) { return false; } try { Class[] args = new Class[] { String.class }; Object[] params = new Object[] { value }; Method m = bean.getClass().getMethod(targetMethod, args); if (m == null) { return false; } m.invoke(bean, params); return true; } catch (java.lang.NoSuchMethodException ex) { return false; } catch (java.lang.reflect.InvocationTargetException ex) { return false; } catch (java.lang.IllegalAccessException ex) { return false; } } public static Object invokeGetMethod(String property, Object bean) { Object returnValue = null; try { Class[] args = new Class[] {}; Object[] params = new Object[] {}; Method m = bean.getClass().getMethod(property, args); if (m == null) { return null; } returnValue = m.invoke(bean, params); return returnValue; } catch (java.lang.NoSuchMethodException ex) { return null; } catch (java.lang.reflect.InvocationTargetException ex) { return null; } catch (java.lang.IllegalAccessException ex) { return null; } } public static boolean binarySearch(String[] a, String aKey) { boolean result = false; if (a == null || a.length == 0 || aKey == null || aKey.equals("")) { return false; } for (int i = 0; i < a.length; i++) { if (aKey.equals(a[i])) { result = true; break; } } return result; } public static double parseDouble(String str) { double f = 0.0; try { f = Double.parseDouble(str); } catch (Exception ex) { // empty } return f; } public static String getSubString(String dateTime, int number) { if (dateTime.length() > number) { dateTime = dateTime.substring(0, number); } return dateTime; } public static String multiplyString(String originNumber, String multiplier) { int nOrigin = 0; int nMultiplier = 0; if ((originNumber == null || originNumber.equals("")) && (multiplier == null || multiplier.equals(""))) { return ""; } try { nOrigin = Integer.parseInt(originNumber); } catch (NumberFormatException e) { return ""; } try { nMultiplier = Integer.parseInt(multiplier); } catch (NumberFormatException e) { return ""; } return (new Integer(nOrigin * nMultiplier).toString()); } public static String divideString(String originNumber, String divisor) { int nOrigin = 0; int nDivisor = 0; if ((originNumber == null || originNumber.equals("")) && (divisor == null || divisor.equals("") || divisor .equals("0"))) { return ""; } try { nOrigin = Integer.parseInt(originNumber); } catch (NumberFormatException e) { return ""; } try { nDivisor = Integer.parseInt(divisor); } catch (NumberFormatException e) { return ""; } return (new Integer(nOrigin / nDivisor).toString()); } /* add by zhaopu 2003-07-21 将页面的请求以map格式放到scoper中 */ public static List getSubstringList(String str, String token) { ArrayList substringList = new ArrayList(); while (str.length() > 0) { int i = str.indexOf(token); String str1 = str.substring(0, i); substringList.add(str1); str = str.substring(i + 1, str.length()); } return substringList; } public static List getPartString(String str, String token) { List substringList = null; int index = str.indexOf(token); if (index != -1) { substringList = new ArrayList(); substringList.add(str.substring(0, index)); substringList.add(str.substring(index + 1, str.length())); } return substringList; } // 将二维数组转换成MAP public static HashMap convertArrayToMap(String flagArray[][]) { HashMap flagHashMap = new HashMap(); for (int i = 0; i < flagArray.length; i++) { flagHashMap.put(flagArray[i][0], flagArray[i][1]); } return (flagHashMap); } // 将字符串按指定的分隔符转换成字符串数组 // zhanglf, 2003-09-04 public static String[] strToArray(String str, String separator) { if (str == null) { return null; } int index = 0; int index2 = 0; index2 = str.indexOf(separator); List list = new ArrayList(); String temp = ""; while (index2 != -1) { temp = str.substring(index, index2); // System.out.println("temp :" + temp); list.add(temp); index = index2 + 1; index2 = str.indexOf(separator, index); if (index2 == -1) { temp = str.substring(index); // System.out.println("temp2 :" + temp); list.add(temp); } } int size = list.size(); String[] arrStr = new String[size]; for (int i = 0; i < size; i++) { arrStr[i] = (String) list.get(i); } // ystem.out.println("list.size :" + list.size()); return arrStr; } /** * 提供精确的加法运算 * * @param v1 * 被加数 * @param v2 * 加数 * @return 两个参数的和 add by dym on 2006-06-12 */ public static double add(String v1, double v2) { BigDecimal b1 = new BigDecimal(v1); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.add(b2).doubleValue(); } // 两个数相乘 public static String mul(String v1, double v2) { if (v1 == null || v1.trim().equals("")) { return ""; } try { BigDecimal b1 = new BigDecimal(v1); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return String.valueOf(b1.multiply(b2).doubleValue()); } catch (Exception ex) { return ""; } } // 相除 public static String div(String v1, double v2) { if (v1 == null || v1.trim().equals("")) { return ""; } try { BigDecimal b1 = new BigDecimal(v1); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return String.valueOf(b1.divide(b2, 10, BigDecimal.ROUND_HALF_UP) .doubleValue()); } catch (Exception ex) { return ""; } } // 相除 public static String div(String v1, String v2, int scale) { if (v1 == null || v1.trim().equals("")) { return ""; } BigDecimal b1 = new BigDecimal(v1); BigDecimal b2 = new BigDecimal(v2); return String.valueOf(b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP) .doubleValue()); } /** * 提供精确的小数位四舍五入处理。 * * @param v * 需要四舍五入的数字 * @param scale * 小数点后保留几位 * @return 四舍五入后的结果 */ public static double round(double v, int scale) { if (scale < 0) { throw new IllegalArgumentException( "The scale must be a positive integer or zero"); } BigDecimal b = new BigDecimal(Double.toString(v)); BigDecimal one = new BigDecimal("1"); return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue(); } public static String replace(String strSource, String strFrom, String strTo) { if (strFrom == null || strFrom.equals("")) { return strSource; } String strDest = ""; int intFromLen = strFrom.length(); int intPos; while ((intPos = strSource.indexOf(strFrom)) != -1) { strDest = strDest + strSource.substring(0, intPos); strDest = strDest + strTo; strSource = strSource.substring(intPos + intFromLen); } strDest = strDest + strSource; return strDest; } public static String getStackTraceText(Exception e) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); e.printStackTrace(new PrintStream(baos)); byte[] buff = baos.toByteArray(); baos.close(); return new String(buff); } catch (Exception ex) { return ""; } } public static String replaceIgnoreCase(String strSource, String strFrom, String strTo) { if (strFrom == null || strFrom.equals("")) { return strSource; } String strDest = ""; int intFromLen = strFrom.length(); int intPos; String tmpStrSource = strSource.toLowerCase(); while ((intPos = tmpStrSource.indexOf(strFrom.toLowerCase())) != -1) { strDest = strDest + strSource.substring(0, intPos); strDest = strDest + strTo; strSource = strSource.substring(intPos + intFromLen); tmpStrSource = strSource.toLowerCase(); } strDest = strDest + strSource; return strDest; } public static Map DTO2Map(Object dto) { HashMap result = new HashMap(); Class dtoClass = dto.getClass(); Method methods[] = dtoClass.getMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; if (method.getName().substring(0, 3).equals("get") && method.getParameterTypes().length == 0 && !method.getName().equals("getClass")) { String key = method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4); Object value = null; try { value = method.invoke(dto, new Object[0]); } catch (Exception e) { } if (value != null) { result.put(key, value); } } } return result; } public static Object Map2DTO(Map map, Object dto) { Class dtoClass = dto.getClass(); Method methods[] = dtoClass.getMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; if (method.getName().substring(0, 3).equals("set") && method.getParameterTypes().length != 0 && !method.getName().equals("setClass") && !method.getName().equals("setRiderDetail11")) { String key = method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4); String value = null; try { value = (String) map.get(key); } catch (Exception e) { } if (value != null) { invokeSetMethod(key, value, dto); } } } return dto; } public static String formatDouble(double num) { String str = num + ""; return str.substring( 0, str.indexOf(".") + (str.length() - str.indexOf(".") >= 3 ? 3 : str .length() - str.indexOf("."))); } public static Object cloneObject(Object obj) { try { java.io.ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(obj); oos.flush(); byte buff[] = baos.toByteArray(); oos.close(); baos.close(); java.io.ByteArrayInputStream bais = new ByteArrayInputStream(buff); ObjectInputStream ois = new ObjectInputStream(bais); Object cloneObj = ois.readObject(); ois.close(); bais.close(); return cloneObj; } catch (Exception e) { e.printStackTrace(); return null; } } public static List copyObject(List fromList, Class toClass) { List toList = new ArrayList(); if (fromList != null && fromList.size() > 0) { Iterator it = fromList.iterator(); while (it.hasNext()) { toList.add(copyObject(it.next(), toClass)); } } return toList; } public static Object copyObject(Object from, Class toClass) { try { Object to = toClass.newInstance(); Class fromClass = from.getClass(); Method methods[] = fromClass.getMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; if (method.getName().substring(0, 3).equals("get") && !method.getName().equals("getClass") && method.getParameterTypes().length == 0) { Class parameterClasses[] = new Class[1]; parameterClasses[0] = method.getReturnType(); Object returnValue = method.invoke(from, new Object[0]); Object parameters[] = new Object[1]; parameters[0] = returnValue; try { Method toMethod = toClass.getMethod("set" + method.getName().substring(3), parameterClasses); toMethod.invoke(to, parameters); } catch (Exception e) { continue; } } } return to; } catch (Exception e) { return null; } } public static Object copyObject(Object from, Object to) { try { Class fromClass = from.getClass(); Method methods[] = fromClass.getMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; if (method.getName().substring(0, 3).equals("get") && !method.getName().equals("getClass") && method.getParameterTypes().length == 0) { Class parameterClasses[] = new Class[1]; parameterClasses[0] = method.getReturnType(); Object returnValue = method.invoke(from, new Object[0]); Object parameters[] = new Object[1]; parameters[0] = returnValue; try { Method toMethod = to.getClass().getMethod( "set" + method.getName().substring(3), parameterClasses); toMethod.invoke(to, parameters); } catch (Exception e) { continue; } } } return to; } catch (Exception e) { return null; } } /** * 转换日期格式 */ public static String convertDateFormat(String strDate, int days) { if (strDate == null || strDate.length() < 10) { return ""; } int year = Integer.parseInt(strDate.substring(0, 4)); int month = Integer.parseInt(strDate.substring(5, 7)); int day = Integer.parseInt(strDate.substring(8, 10)); Calendar cld = Calendar.getInstance(); cld.set(year, month - 1, day); if (days != -1) { cld.add(Calendar.DATE, days); } String yy = new Integer(cld.get(Calendar.YEAR)).toString(); String mm = new Integer(cld.get(Calendar.MONTH) + 1).toString(); String dd = new Integer(cld.get(Calendar.DATE)).toString(); if (mm.length() < 2) mm = "0" + mm; if (dd.length() < 2) dd = "0" + dd; if (days != -1) { return yy + "年" + mm + "月" + dd + "日"; } else { return yy + mm + dd; } } public static String convertSimpleDateFormat(String strDate) { if (strDate == null || strDate.length() < 10) { return ""; } int year = Integer.parseInt(strDate.substring(0, 4)); int month = Integer.parseInt(strDate.substring(5, 7)); int day = Integer.parseInt(strDate.substring(8, 10)); Calendar cld = Calendar.getInstance(); cld.set(year, month - 1, day); String yy = new Integer(cld.get(Calendar.YEAR)).toString(); String mm = new Integer(cld.get(Calendar.MONTH) + 1).toString(); String dd = new Integer(cld.get(Calendar.DATE)).toString(); if (mm.length() < 2) mm = "0" + mm; if (dd.length() < 2) dd = "0" + dd; return yy + mm + dd; } private static String toChinese(String sStr, String sFour, int i, boolean bPre) { String sStruct = "";// 回传结果 for (int j = 0; j < 4; j++) { if (sFour.charAt(j) != ‘0‘)// 处理每一位数值时,在前面是否需要加“零” { if (j == 0)// 处理千位 { if (!bPre) { sStruct = sStruct + ‘0‘; } sStruct = sStruct + sFour.charAt(j); } else// 处理百、十、个位 { if (sFour.charAt(j - 1) == ‘0‘) { sStruct = sStruct + ‘0‘; } sStruct = sStruct + sFour.charAt(j); } switch (j)// 单独处理“角”和“分” { case 0: { if (i == 3) { sStruct = sStruct + ‘角‘; } else { sStruct = sStruct + ‘仟‘; } break; } case 1: { if (i == 3) { sStruct = sStruct + ‘分‘; } else { sStruct = sStruct + ‘佰‘; } break; } case 2: { sStruct = sStruct + ‘拾‘; break; } case 3: { if (!sStruct.equals("")) { switch (i)// 处理单位 { case 0: { sStruct = sStruct + "亿"; break; } case 1: { sStruct = sStruct + "万"; break; } case 2: { sStruct = sStruct + "元"; break; } } } } } } else// 当个位为零时,处理单位 { if (!sStruct.equals("") && j == 3) { switch (i) { case 0: { sStruct = sStruct + "亿"; break; } case 1: { sStruct = sStruct + "万"; break; } } } if (i == 2 && j == 3 && (!sStr.equals("") || !sStruct.equals("")))// 是否加“元”字 { sStruct = sStruct + "元"; } } } return sStruct; } // 参数digit最多有两位小数,本方法最大支持金额999999999999.99 public static String toUpper(double digit) { // 将数据格式化为四位小数 DecimalFormat df = new DecimalFormat("#.0000"); StringBuffer sbDigit = new StringBuffer(df.format(digit)); sbDigit.replace(sbDigit.length() - 2, sbDigit.length(), "00"); String sDigit = "";// 将double转化为string sDigit = sbDigit.toString(); sDigit = sDigit.substring(0, sDigit.length() - 5) + sDigit.substring(sDigit.length() - 4);// 去除小数点 // 将字符串补齐16位,利于分组 // sDigit = sDigit + "00"; if (sDigit.length() > 16) { return "款项过大!"; } if (sDigit.length() < 16) { int iLength = 16 - sDigit.length(); for (int i = 0; i < iLength; i++) { sDigit = "0" + sDigit; } } if (sDigit.equals("0000000000000000")) { return "零元整"; } String sChinese = sDigit; String sFour = "";// 每四位构造一个string boolean bPreStr = true;// 前一个string是否构造成功 sDigit = "";// 总字符串 // 将字符串分为四组,每一组单独处理,都处理完后串接 for (int i = 0; i < 4; i++) { sFour = toChinese(sDigit, sChinese.substring(i * 4, i * 4 + 4), i, bPreStr); if (sFour.length() == 0 || sFour.length() == 1) { bPreStr = false; } else if (sFour.charAt(sFour.length() - 2) < ‘0‘ || sFour.charAt(sFour.length() - 2) > ‘9‘) { bPreStr = false; } else { bPreStr = true; } sDigit = sDigit + sFour; } // 去掉字符串最前面的‘0’ for (;;) { if (sDigit.charAt(0) == ‘0‘) { sDigit = sDigit.substring(1); } else { break; } } sChinese = ""; for (int i = 0; i < sDigit.length(); i++) { if (sDigit.charAt(i) >= ‘0‘ && sDigit.charAt(i) <= ‘9‘) { switch (sDigit.charAt(i)) { case ‘1‘: { sChinese = sChinese + "壹"; break; } case ‘2‘: { sChinese = sChinese + "贰"; break; } case ‘3‘: { sChinese = sChinese + "叁"; break; } case ‘4‘: { sChinese = sChinese + "肆"; break; } case ‘5‘: { sChinese = sChinese + "伍"; break; } case ‘6‘: { sChinese = sChinese + "陆"; break; } case ‘7‘: { sChinese = sChinese + "柒"; break; } case ‘8‘: { sChinese = sChinese + "捌"; break; } case ‘9‘: { sChinese = sChinese + "玖"; break; } case ‘0‘: { sChinese = sChinese + "零"; break; } } } else { sChinese = sChinese + sDigit.charAt(i); } } if (!sDigit.endsWith("分"))// 有"分"不加"整" { sChinese = sChinese + "整"; } return sChinese; } public static List splitByChinese(String value) { List result = new ArrayList(); if (value == null) { return result; } String buff = ""; for (int i = 0; i < value.length(); i++) { if (value.substring(i, i + 1).getBytes().length == 1) { buff = buff + value.substring(i, i + 1); } else { if (buff != "") { result.add(buff); } result.add(value.substring(i, i + 1)); buff = ""; } } if (buff != "") { result.add(buff); } return result; } public static String getScript(Object obj) { return getScript(obj, ""); } public static String getScript(Object obj, String prefix) { List classFilter = new ArrayList(); classFilter.add(String.class); classFilter.add(Integer.class); classFilter.add(Double.class); classFilter.add(Float.class); classFilter.add(Boolean.class); classFilter.add(java.sql.Timestamp.class); if (obj == null) return ""; // String ret = ""; StringBuffer ret = new StringBuffer(""); Class c = obj.getClass(); Method methods[] = c.getMethods(); for (int i = 0; i < methods.length; i++) { if (methods[i].getParameterTypes().length > 0 || !methods[i].getName().substring(0, 3).equals("get")) { continue; } String propertyName = methods[i].getName().substring(3, 4) .toLowerCase() + methods[i].getName().substring(4); if (!propertyName.equals("script") && !propertyName.equals("class")) try { Object result = methods[i].invoke(obj, new Object[0]); if (classFilter.contains(result.getClass())) ret.append("try{setValue(document.all[\"" + prefix + propertyName + "\"],\"" + result.toString() + "\");}catch(ex){}"); else if (result.getClass().equals(ArrayList.class)) for (int j = 0; j < ((List) result).size(); j++) ret.append(getScript(((List) result).get(j), propertyName + "[" + j + "].")); else ret.append(getScript(result, propertyName + ".")); } catch (Exception e) { } } return ret.toString(); } public static String getServletName(String url) { if (url.indexOf("/") < 0) return url; else return getServletName(url.substring(url.indexOf("/") + 1)); } public static String getWebContentByURL(String urlString) { try { URL url = new URL(urlString); InputStream is = url.openStream(); BufferedReader reader = new BufferedReader( new InputStreamReader(is)); StringBuffer buff = new StringBuffer(); while (true) { String line = reader.readLine(); if (line == null) break; buff.append(line); } reader.close(); is.close(); return buff.toString(); } catch (MalformedURLException ex) { return null; } catch (IOException ex) { return null; } } public static String getSubStr(String str1, String str2) { String returnStr = null; if (str1 == null || str1.length() == 0) { returnStr = ""; } else if (str2 == null || str2.length() == 0) { returnStr = str1; } else if (str1.lastIndexOf(str2) == -1) { returnStr = str1; } else { returnStr = str1.substring(0, str1.lastIndexOf(str2)); } return returnStr; } /** * fuction:str1检查是否匹配字符串 param str2 匹配的字符串 return : 匹配到了 返回true 否则 false * * @param str1 * @param str2 * @return */ public static boolean checkStr(String str1, String str2) { boolean bl = false; if (str1 == null) return false; if (str2 == null) return false; for (int i = 0; i < str1.length(); i++) { String s = str1.substring(i, i + 1); if (s.equals(str2)) { bl = true; break; } } return bl; } public static Date convertStringToDate(String date, String formatPattern) { SimpleDateFormat sdf = new SimpleDateFormat(); if (formatPattern == null || formatPattern.equals("")) { formatPattern = "yyyy-MM-dd HH:mm:ss"; } sdf.applyPattern(formatPattern); try { return sdf.parse(date); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } } public static final String QBchange(String QJstr) { String outStr = ""; String Tstr = ""; byte[] b = null; for (int i = 0; i < QJstr.length(); i++) { try { Tstr = QJstr.substring(i, i + 1); b = Tstr.getBytes("unicode"); } catch (java.io.UnsupportedEncodingException e) { e.printStackTrace(); } if (b[3] == -1) { b[2] = (byte) (b[2] + 32); b[3] = 0; try { outStr = outStr + new String(b, "unicode"); } catch (java.io.UnsupportedEncodingException e) { e.printStackTrace(); } } else outStr = outStr + Tstr; } return outStr; } /** * 去掉字符串内部的空格 * * @param targetValue * 需要去除空格的字符串 * @return */ public static final String trimInnerSpace(String targetValue) { if (null == targetValue || "".equals(targetValue)) { return targetValue; } else { return targetValue.trim().replaceAll(" ", ""); } } /** * 将投保平台的证件类型转换成cif2标准证件类型 * * @param 投保平台的证件类型 * @return 标准证件类型 * @see 没有找到对应的类型就置为0(其他) */ public static final String convertCertificateType(String type) { return type == null ? null : (certificateTypeMap.get(type) == null ? "0" : (String) certificateTypeMap.get(type)); } /** * 判断是否境外旅行意外险产品 * * @param planCode * @param productCode * @return */ public static boolean isAbroadAccident(String planCode, String productCode) { return (("Y009".equals(planCode)) && ("00033".equals(productCode) || "00034".equals(productCode) || "00035".equals(productCode) || "00036".equals(productCode) || "00037".equals(productCode) || "00038" .equals(productCode))) || (("Y064".equals(planCode)) && ("00708".equals(productCode) || "00709".equals(productCode) || "00710".equals(productCode) || "00711".equals(productCode) || "00712".equals(productCode) || "00713" .equals(productCode))); } private static final String[] EMAIL_APPENDIX = new String[] { ".paic.com.cn", ".pingan.com.cn", ".pingan.com" }; public static boolean isEmailEqual(String a, String b) { if (StringUtils.hasText(a) && StringUtils.hasText(b)) { a = a.toLowerCase(); b = b.toLowerCase(); for (int i = 0; i < EMAIL_APPENDIX.length; i++) { if (a.endsWith(EMAIL_APPENDIX[i])) { a = a.substring(0, a.indexOf(EMAIL_APPENDIX[i])); } if (b.endsWith(EMAIL_APPENDIX[i])) { b = b.substring(0, b.indexOf(EMAIL_APPENDIX[i])); } } return a.equals(b); } return false; } /** * 比较两个双精度浮点数是否相等 * * @param a * @param b * @return */ public static boolean isDoubleNumberEqual(double a, double b) { if (Math.abs(a - b) < 0.00001) { return true; } else { return false; } } /** * 身份证18位转换为15位 * * @param icNo * @return */ public static String IdentityCardNo18to15(String icNo) { if (icNo == null || "".equals(icNo.trim())) { return ""; } String newIcNo = icNo.trim(); if (newIcNo.length() != 18) { return icNo; } else { return newIcNo.substring(0, 6) + newIcNo.substring(8, 17); } } /** * 厦门结案区间 * * @param type * @return */ public static String getCaseName(String type) { return type == null ? "" : (caseMap.get(type) == null ? "" : (String) caseMap.get(type)); } /** * <p> * 判断给定字符串是否为null或"" * * @param s * @return true或false */ public static boolean isEmptyStr(String s) { if (s == null || s.trim().length() == 0) { return true; } else { return false; } } /** * <p> * 判断给定字符串是否为null或"" * * @param s * @return 不为空返回true,否则false */ public static boolean isNotEmptyStr(String s) { return !isEmptyStr(s); } /** * 计算两个日期的间隔年数 * * @author zsx * @param smallDateStr * ,bigDateStr * @return float year (小数部分没有四舍五入) */ public static double getYearBetweenTowDate(String smallDateStr, String bigDateStr) { double year = 0; if (CommonFunctions.isNotEmptyStr(smallDateStr) && CommonFunctions.isNotEmptyStr(bigDateStr)) { try { java.util.Date smallDate = CommonFunctions .parseTime(smallDateStr); java.util.Date bigDate = CommonFunctions.parseTime(bigDateStr); int smallYear = smallDate.getYear() + 1900; int smallMonth = smallDate.getMonth() + 1; int smallDay = smallDate.getDate(); int bigYear = bigDate.getYear() + 1900; int bigMonth = bigDate.getMonth() + 1; int bigDay = bigDate.getDate(); year = (bigYear - smallYear) + (bigMonth - smallMonth) / 12.0 + (bigDay - smallDay) / 365.0; } catch (Exception e) { e.printStackTrace(); } } return year; } /** * zxs 2008-05-07 比较两日期大小,日期1大于等于日期2 返回1,小于返回-1,等于返回0 精确到时分秒 */ public static int compareDates(String dateStr1, String dateStr2) { java.util.Date date1 = parseTime(dateStr1); java.util.Date date2 = parseTime(dateStr2); int result = date1.compareTo(date2); return result; } /** * 将常用时间字符串转换为时间对象 zxs 2007-12-25 修改归并版本有两个parseTime方法问题 * * @param String * @return java.util.Date */ public static java.util.Date parseTime(String date) { SimpleDateFormat df = new SimpleDateFormat(); java.util.Date rtnDate = null; if (date == null || date.trim().equals("") || date.trim().equals("null")) return rtnDate; try { date = date.trim(); int length = date.length(); if (date.indexOf("-") != -1) { if (length == 5) { if (date.indexOf("-") == length - 1) {// 2008- df.applyPattern("yyyy"); date = date.substring(0, 4); rtnDate = df.parse(date); } else { df.applyPattern("yyyy-MM");// 2008-01 rtnDate = df.parse(date); } } else if (length >= 6 && length <= 7) {// 2008-1 -- 2008-01 df.applyPattern("yyyy-MM"); rtnDate = df.parse(date); } else if (length >= 8 && length <= 9) { if (date.lastIndexOf("-") == length - 1) { // 2008-12- df.applyPattern("yyyy-MM"); date = date.substring(0, length - 1); rtnDate = df.parse(date); } else { df.applyPattern("yyyy-MM-dd");// 2008-1-1 -- 2008-01-01 rtnDate = df.parse(date); } } else if (length >= 10 && length <= 11) { if (date.indexOf(" ") > -1 && date.indexOf(" ") < length - 1) { df.applyPattern("yyyy-MM-dd HH");// 2008-1-1 1 -- // 2008-1-1 11 中间有空格 rtnDate = df.parse(date); } else { df.applyPattern("yyyy-MM-dd");// "2008-01-01"中间无空格 rtnDate = df.parse(date); } } else if (length >= 12 && length <= 13) { if (date.indexOf(":") > -1 && date.indexOf(":") < length - 1) { df.applyPattern("yyyy-MM-dd HH:mm");// 2008-1-1 1:1 -- // 2008-1-1 1:01 // 中间有冒号 rtnDate = df.parse(date); } else { df.applyPattern("yyyy-MM-dd HH");// 2008-01-01 01 中间有空格 rtnDate = df.parse(date); } } else if (length >= 14 && length <= 16) { int lastIndex = date.lastIndexOf(":"); if (date.indexOf(":") > -1 && lastIndex < length - 1 && date.indexOf(":") != lastIndex) { df.applyPattern("yyyy-MM-dd HH:mm:ss");// 2008-1-1 1:1:1 // -- 2008-01-01 // 1:1:1 中间有两个冒号 if (lastIndex < length - 1 - 2) { date = date.substring(0, lastIndex + 3); } rtnDate = df.parse(date); } else if (date.indexOf(":") > -1 && lastIndex < length - 1 && date.indexOf(":") == lastIndex) { df.applyPattern("yyyy-MM-dd HH:mm");// 2008-01-01 1:1 -- // 2008-01-01 // 01:01中间只有一个冒号 rtnDate = df.parse(date); } else if (date.indexOf(":") > -1 && lastIndex == length - 1 && date.indexOf(":") == lastIndex) { df.applyPattern("yyyy-MM-dd HH");// 2008-01-01 01: // 只有一个冒号在末尾 date = date.substring(0, length - 1); rtnDate = df.parse(date); } } else if (length == 17) { int lastIndex = date.lastIndexOf(":"); if (lastIndex < length - 1) { df.applyPattern("yyyy-MM-dd HH:mm:ss");// 2008-1-1 1:1:1 // -- 2008-01-01 // 1:1:1 中间有两个冒号 if (lastIndex < length - 1 - 2) { date = date.substring(0, lastIndex + 3); } rtnDate = df.parse(date); } else if (lastIndex == length - 1) { df.applyPattern("yyyy-MM-dd HH:mm");// 2008-01-01 1:1 -- // 2008-01-01 // 01:01中间只有一个冒号 date = date.substring(0, length - 1); rtnDate = df.parse(date); } } else if (length >= 18) { df.applyPattern("yyyy-MM-dd HH:mm:ss");// 2008-1-1 1:1:1 -- // 2008-01-01 // 01:01:01 有两个冒号 int lastIndex = date.lastIndexOf(":"); if (lastIndex < length - 1 - 2) { date = date.substring(0, lastIndex + 3); } rtnDate = df.parse(date); } } else if (length == 4) { df.applyPattern("yyyy"); rtnDate = df.parse(date); } else if (length >= 5 && length <= 6) { df.applyPattern("yyyyMM"); rtnDate = df.parse(date); } else if (length >= 7 && length <= 8) { df.applyPattern("yyyyMMdd"); rtnDate = df.parse(date); } else if (length >= 9 && length <= 10) { df.applyPattern("yyyyMMddHH"); rtnDate = df.parse(date); } else if (length >= 11 && length <= 12) { df.applyPattern("yyyyMMddHHmm"); rtnDate = df.parse(date); } else if (length >= 13 && length <= 14) { df.applyPattern("yyyyMMddHHmmss"); rtnDate = df.parse(date); } else if (length >= 15) { df.applyPattern("yyyyMMddHHmmss"); date = date.substring(0, 14); rtnDate = df.parse(date); } } catch (Exception ex) { ex.printStackTrace(); } return rtnDate; } public static int parseInt(String str) { int f = 0; try { if (str == null || str.trim().equals("")) { f = 0; } else { f = Integer.parseInt(str); } } catch (Exception ex) { f = 0; } return f; } /** * 去掉字符串中的中文字符 * * @param str * @return */ public static String deleteChainese(String str) { if (str == null || "null".equals(str.trim()) || "".equals(str.trim())) { return ""; } String returnStr = str; try { String regEx = "[\\u4e00-\\u9fa5]"; Pattern p = Pattern.compile(regEx); Matcher m = p.matcher(str); while (m.find()) { for (int i = 0; i <= m.groupCount(); i++) { returnStr = returnStr.replaceAll(m.group(i), ""); } } } catch (Exception ex) { returnStr = str; } return returnStr.trim(); } /** * 去掉字符串中的[非]中文字符 * * @param str * @return */ public static String deleteNotChinese(String str) { if (str == null || "null".equals(str.trim()) || "".equals(str.trim())) { return ""; } String returnStr = str; try { returnStr = returnStr.replaceAll("[^\\u4e00-\\u9fa5]", ""); } catch (Exception ex) { returnStr = str; } return returnStr.trim(); } /** * 返回单精度数值 added by wangxf 2005-12-20 * * @param str * String * @return float */ public static float parseFloat(String str) { float f = 0; if (str != null && !"".equals(str)) { str = str.trim(); try { f = Float.parseFloat(str); } catch (Exception ex) { f = 0; } } return f; } /** * 取保险止期优化 wuxiangrong001 yyyy-mm-dd converted to yyyy-mm-dd 23:59:59 */ public static String convertContractEndDate(String contractEndDate) { if (StringUtils.hasText(contractEndDate)) { return formatDate(parseDate(contractEndDate, "yyyy-MM-dd")) + " 23:59:59"; } else { return contractEndDate; } } public static String[] convertCurrencyCode(String currencyCode) { if ("01".equals(currencyCode)) { return new String[] { "RMB", "元" }; } else if ("02".equals(currencyCode)) { return new String[] { "HKD", "元" }; } else if ("03".equals(currencyCode)) { return new String[] { "USD", "元" }; } else if ("04".equals(currencyCode)) { return new String[] { "GBP", "元" }; } else if ("05".equals(currencyCode)) { return new String[] { "JPY", "元" }; } else if ("06".equals(currencyCode)) { return new String[] { "DM", "元" }; } else if ("07".equals(currencyCode)) { return new String[] { "SF", "元" }; } else if ("08".equals(currencyCode)) { return new String[] { "FF", "元" }; } else if ("09".equals(currencyCode)) { return new String[] { "SGD", "元" }; } else if ("10".equals(currencyCode)) { return new String[] { "CAD", "元" }; } else if ("11".equals(currencyCode)) { return new String[] { "NTD", "元" }; } else if ("12".equals(currencyCode)) { return new String[] { "EUR", "元" }; } else if ("13".equals(currencyCode)) { return new String[] { "AUD", "元" }; } else if ("14".equals(currencyCode)) { return new String[] { "ITL", "元" }; } else if ("15".equals(currencyCode)) { return new String[] { "NLG", "元" }; } else if ("16".equals(currencyCode)) { return new String[] { "ATS", "元" }; } else if ("17".equals(currencyCode)) { return new String[] { "BEF", "元" }; } else if ("18".equals(currencyCode)) { return new String[] { "MOP", "元" }; } else if ("19".equals(currencyCode)) { return new String[] { "NLG", "克朗" }; } else if ("20".equals(currencyCode)) { return new String[] { "NOK", "克朗" }; } else if ("21".equals(currencyCode)) { return new String[] { "SEK", "克朗" }; } else if ("22".equals(currencyCode)) { return new String[] { "NZD", "元" }; } else if ("23".equals(currencyCode)) { return new String[] { "COREA", "元" }; } else { return new String[] { "RMB", "元" }; } } // describe object public static Map describe(Object obj) { if (obj == null) { return Collections.EMPTY_MAP; } else { try { return BeanUtils.describe(obj); } catch (Exception e) { // ignore the exception; return Collections.EMPTY_MAP; } } } // remove the map that the null or empty value; public static void purifyMap(Map one) { if (one != null && !one.isEmpty()) { List uselessKeys = new ArrayList(one.size() / 2); for (Iterator it = one.keySet().iterator(); it.hasNext();) { Object key = it.next(); Object value = one.get(key); // record useless keys; if (value == null) { uselessKeys.add(key); } else if ((value instanceof String) && !StringUtils.hasText((String) value)) { uselessKeys.add(key); } } for (int i = 0; i < uselessKeys.size(); i++) { Object key = uselessKeys.get(i); one.remove(key); } // clear; uselessKeys.clear(); uselessKeys = null; } } public static void main(String[] args) { int interval = 0; try { interval = getDays("2018-03-10", "2018-03-20"); System.out.println(interval); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }