工具类,操作字符串、日期、图像、IO等

来源:互联网 发布:双敏网络精灵 编辑:程序博客网 时间:2024/05/22 00:25
package com.gameqp.common;import java.awt.Color;import java.awt.Font;import java.awt.Graphics2D;import java.awt.RenderingHints;import java.awt.geom.AffineTransform;import java.awt.geom.Line2D;import java.awt.image.BufferedImage;import java.io.IOException;import java.io.InputStream;import java.math.BigDecimal;import java.math.BigInteger;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import java.text.NumberFormat;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.Date;import java.util.GregorianCalendar;import java.util.Iterator;import java.util.List;import java.util.Properties;import java.util.regex.Matcher;import java.util.regex.Pattern;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;/** * 工具类,操作字符串、日期、图像、IO等 *  * @author duhai *  */public class Utils {private static Log log = LogFactory.getLog(Utils.class);private static String APP_CONFIG="/app.properties";/** * 内部类,字符串操作 *  * @author *  */public static class Str {/** * 随机验证码 *  * @author duhai * @param count * @return */public static String rndCode(int count) {if (count < 0) {return "";}char[] array = new char[] { '8', '5', '4', '2', '9', '3', '7', '6','A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M','N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z','a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n','p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'y', 'z' };StringBuffer sb = new StringBuffer();for (int i = 0; i < count; i++) {int index = (int) (Math.random() * array.length);sb.append(array[index]);}return sb.toString();}/** * 判断字符串是否为空,包括null、空字符串和空格 *  * @param str *            字符串 * @return 是或否 */public static boolean isEmpty(String str) {if (str == null || str.trim().equals("")|| str.trim().equalsIgnoreCase("null")) {return true;}return false;}/** * 将null转为空字符串 *  * @param str *            字符串 * @return */public static String nullToEmpty(String str) {if (str == null) {return "";}return str;}/** * 空字符串和null字符串转换为null * @param str * @return */public static String emptyToNull(String str) {if (str.trim().equals("") || str.trim().equalsIgnoreCase("null")) {return null;} return str;}/** * 返回字符串的字符数,无论为汉字、数字或字母,均为1个长度 *  * @param str *            字符串 * @return 字符个数 */public static int getLength(String str) {if (str == null || str.equals("")) {return 0;}return str.length();}/** * 返回字符串的字节数,汉字为2个长度,字母或数字为1个长度 *  * @param str *            字符串 * @return 字节个数 */public static int getByteLength(String str) {if (str == null || str.equals("")) {return 0;}return str.getBytes().length;}/** * 判断Integer为null时的处理 * @param integer * @return */public static int getIntegerValue(Integer integer){if (null == integer){return 0;}return integer;}/** * 判断Double为null时的处理 * @param dble * @return */public static double getDoubleValue(Object str){if (null == str) {return 0.00;}return Double.parseDouble(str.toString());}/** * 判断字符串是否为英文、数字和下划线组合,且以英文或下划线开头 *  * @param str * @return */public static boolean isWord(String str) {if (str == null) {return false;}if (!str.matches("[A-Za-z_][A-Za-z0-9_]*")) {return false;}return true;}/** * 判断字符串是否为整数 *  * @param str *            字符串 * @return 是或否 */public static boolean isInt(String str) {if (str == null) {return false;}if (!str.matches("([+-]?[1-9][0-9]*)|0")) {return false;}BigInteger bi = new BigInteger(str);BigInteger minValue = new BigInteger(String.valueOf(Integer.MIN_VALUE));BigInteger maxValue = new BigInteger(String.valueOf(Integer.MAX_VALUE));if (bi.compareTo(minValue) < 0 || bi.compareTo(maxValue) > 0) {return false;}return true;}/** * 判断字符串是否为小数,且小数最多为几个,当maxFraction为-1时忽略小数位数的判断 *  * @param str *            字符串 * @param maxFraction *            小数允许的最大个数 * @return 是或否 */public static boolean isDecimal(String str, int maxFraction) {if (str == null) {return false;}if (!str.matches("([+-]?[1-9][0-9]*)|([+-]?[1-9][0-9]*\\.[0-9]+)|([+-]?0\\.[0-9]+)")) {return false;}if (maxFraction != -1) {if (!str.matches("([+-]?[1-9][0-9]*)|([+-]?[1-9][0-9]*\\.[0-9]{1,"+ maxFraction+ "})|([+-]?0\\.[0-9]{1,"+ maxFraction+ "})")) {return false;}}return true;}/** * 判断字符串是否为日期型 *  * @param str *            字符串 * @return 是或否 */public static boolean isDate(String str) {if (str == null) {return false;}Pattern pattern = Pattern.compile("(\\d{4})\\-(\\d{1,2})\\-(\\d{1,2})");Matcher matcher = pattern.matcher(str);if (!matcher.matches()) {return false;}int year = Integer.parseInt(matcher.group(1));int month = Integer.parseInt(matcher.group(2));int day = Integer.parseInt(matcher.group(3));boolean isLeap = false;if (year % 4 == 0 && year % 100 != 0) {isLeap = true;} else {if (year % 400 == 0) {isLeap = true;}}if (month < 1 || month > 12) {return false;} else {if (day < 1 || day > 31) {return false;} else {if (month == 4 || month == 6 || month == 9 || month == 11) {if (day == 31) {return false;}} else {if (month == 2) {if (isLeap) {if (day > 29) {return false;}} else {if (day > 28) {return false;}}}}}}return true;}/** * 判断字符串是否为日期时间型 *  * @param str *            字符串 * @return 是或否 */public static boolean isDatetime(String str) {if (str == null) {return false;}Pattern pattern = Pattern.compile("(\\d{4})\\-(\\d{1,2})\\-(\\d{1,2})\\s(\\d{1,2}):(\\d{1,2})");Matcher matcher = pattern.matcher(str);if (!matcher.matches()) {return false;}int year = Integer.parseInt(matcher.group(1));int month = Integer.parseInt(matcher.group(2));int day = Integer.parseInt(matcher.group(3));int hour = Integer.parseInt(matcher.group(4));int minute = Integer.parseInt(matcher.group(5));boolean isLeap = false;if (year % 4 == 0 && year % 100 != 0) {isLeap = true;} else {if (year % 400 == 0) {isLeap = true;}}if (month < 1 || month > 12) {return false;} else {if (day < 1 || day > 31) {return false;} else {if (month == 4 || month == 6 || month == 9 || month == 11) {if (day == 31) {return false;}} else {if (month == 2) {if (isLeap) {if (day > 29) {return false;}} else {if (day > 28) {return false;}}}}}}if (hour > 23 || minute > 59) {return false;}return true;}/** * 验证字符串是否为手机号 *  * @param str *            字符串 * @return 是或否 */public static boolean isMobileNumber(String str) {if (str == null) {return false;}return str.matches("1[3-8]\\d{9}");}/** * 验证字符串是否为邮箱 *  * @param str *            字符串 * @return 是或否 */public static boolean isEmail(String str) {if (str == null) {return false;}return str.matches("\\w+@(\\w+\\.\\w+)+");}/** * 验证字符串是否为身份证号 *  * @param str *            字符串 * @return 是或否 */public static boolean isIdcardNumber(String str) {if (str == null) {return false;}str = str.toUpperCase();if (!str.matches("(\\d{18})|(\\d{17}X)")) {return false;}String regionCode = str.substring(0, 6);String birthday = str.substring(6, 14);String verifyCode = str.substring(17);// 验证区域码if (regionCode.compareTo("110000") < 0) {return false;} else {if (regionCode.compareTo("659004") > 0) {if (!regionCode.equals("710000")&& !regionCode.equals("810000")&& !regionCode.equals("820000")) {return false;}}}// 验证生日String stdBirthday = birthday.substring(0, 4) + "-"+ birthday.substring(4, 6) + "-" + birthday.substring(6);if (!isDate(stdBirthday)) {return false;}// 验证校验码是否正确final int power[] = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5,8, 4, 2 };int sum = 0;char[] chars = str.toCharArray();for (int i = 0; i < 17; i++) {sum = sum + Integer.parseInt(String.valueOf(chars[i]))* power[i];}int intVerifyCode = sum % 11;final String[] SEQCODES = new String[] { "1", "0", "X", "9", "8","7", "6", "5", "4", "3", "2" };if (!SEQCODES[intVerifyCode].equals(verifyCode)) {return false;}return true;}/** * 生成随机字符串 *  * @param count *            字符个数 * @return */public static String rnd(int count) {if (count < 0) {return "";}char[] array = new char[] { '8', '5', '4', '0', '1', '2', '9', '3','7', '6' };StringBuffer sb = new StringBuffer();for (int i = 0; i < count; i++) {int index = (int) (Math.random() * array.length);sb.append(array[index]);}return sb.toString();}/** * 将HTML转成纯文本 *  * @param str *            HTML格式的字符串 * @return */public static String htmlToText(String str) {// 含html标签的字符串String text = str;// 过滤script标签Pattern p = Pattern.compile("<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>",Pattern.CASE_INSENSITIVE);Matcher m = p.matcher(text);text = m.replaceAll("");// 过滤style标签p = Pattern.compile("<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>",Pattern.CASE_INSENSITIVE);m = p.matcher(text);text = m.replaceAll("");// 过滤html标签p = Pattern.compile("<[^>]+>", Pattern.CASE_INSENSITIVE);m = p.matcher(text);text = m.replaceAll("");return text;}/** * 将文本域的字符串转成数据库字符串 *  * @param str *            字符串 * @return */public static String fieldToDb(String str) {String dbText = str;dbText.replaceAll(" ", " ");dbText.replaceAll("<", "<");dbText.replaceAll(">", ">");dbText.replaceAll("\r", "<br />");return dbText;}/** * 将数据库字符串转成文本域的字符串 *  * @param str *            字符串 * @return */public static String dbToField(String str) {String fieldText = str;fieldText.replaceAll(" ", " ");fieldText.replaceAll("<br[\\s]*/>", "\r");fieldText.replaceAll("<", "<");fieldText.replaceAll(">", ">");return fieldText;}/** * 把一个字符串转换成int数组 * @param str eg(1,2,3) * @param egx eg(,) * @return */public static int[] toIntArray(String str,String egx) {int[] arr_i = new int[0];;String[] arr_s = null;if (!isEmpty(str)) {arr_s = str.split(egx);}if (arr_s!=null) {arr_i = new int[arr_s.length]; for(int i=0;i<arr_s.length;i++){arr_i[i]=FormatUtil.parseInt(arr_s[i]);}}return arr_i;}/** * 检查一个字符串是否存在某个数组中 * @param s * @param str * @return */public static boolean isExist(String[] s,String str){boolean bool = false;try {if (s!=null && s.length>0 && !isEmpty(str)) {for (int i = 0; i < s.length; i++) {if (s[i].equals(str)) {bool=true;break;}}}} catch (Exception e) {bool = false;}return bool;}/** * 去掉字符串首尾指定的符号 * @param handstr * @param c * @return */public static String delSpeciChar(String handstr,String c){if (Str.isEmpty(handstr) || Str.isEmpty(c)) {return handstr;}String rstr = handstr;int isgoon = 0;String s_begin = handstr.substring(0,1);String s_end = handstr.substring(handstr.length()-1, handstr.length());if (c.equals(s_begin)) {rstr = rstr.substring(1, rstr.length());}else{isgoon++;}if (c.equals(s_end)) {rstr = rstr.substring(0, rstr.length()-1);}else{isgoon++;}if(isgoon<2){return delSpeciChar(rstr,c);}else{return rstr;}}/** *  * @Method: listsToStr  * @Description: (循环list每项用 指定字符串 隔开 然后拼起来返回)  * @param lstr 集合  * @return String 每项以 指定字符串 分开的格式返回 *  * @author Mr.cheng  * @date 2016年11月26日 下午2:45:21  */public static String listsToStr(List<String> lstr,String rexp){String str="";try {if (lstr!=null && lstr.size()>0) {Iterator<String> ls = lstr.iterator();while (ls.hasNext()) {str+=ls.next()+rexp;}}} catch (Exception e) {e.printStackTrace();}return str.substring(0,str.length()-1);}}/** * 32位MD5加密工具类 */public static class MD5 {/** * 将字符串转成32位加密字符串 *  * @param str *            明码 * @return 密码 */public static String md5(String str) {MessageDigest messageDigest = null;try {messageDigest = MessageDigest.getInstance("MD5");messageDigest.reset();messageDigest.update(str.getBytes("UTF-8"));} catch (IOException e) {log.error(e.getMessage());} catch (NoSuchAlgorithmException e) {log.error(e.getMessage());}byte[] byteArray = messageDigest.digest();StringBuffer md5StrBuff = new StringBuffer();for (int i = 0; i < byteArray.length; i++) {if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) {md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));} else {md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));}}return md5StrBuff.toString();}}/** * 图片工具类 *  * @author duhai *  */public static class ImgUtil {/** * 根据指定的字符串生成验证码图片 *  * @param str *            字符串 * @return 图片对象 */public static BufferedImage createAuthcodeImage(String str) {int width = 70;int height = 28;// 生成白底空图片BufferedImage bi = new BufferedImage(width, height,BufferedImage.TYPE_3BYTE_BGR);Graphics2D g2 = (Graphics2D) bi.getGraphics();g2.setColor(Color.WHITE);g2.fillRect(0, 0, width, height);// 干扰线for (int i = 0; i < 10; i++) {int x1 = (int) (Math.random() * width);int y1 = (int) (Math.random() * height);int x2 = (int) (Math.random() * (width - 3));int y2 = (int) (Math.random() * (height - 3));Line2D line = new Line2D.Double(x1, y1, x2, y2);int r = (int) (Math.random() * 255);int g = (int) (Math.random() * 255);int b = (int) (Math.random() * 255);g2.setColor(new Color(r, g, b));g2.draw(line);}// 将字符拆散,设置随机大小和倾斜角度for (int i = 0; i < str.length(); i++) {String ch = String.valueOf(str.charAt(i));// 字体颜色int r = (int) (Math.random() * 128);int g = (int) (Math.random() * 128);int b = (int) (Math.random() * 128);// 字体大小int rnd = (int) (Math.random() * 5);int fontSize = 20;// 设置Y方向的偏移量int y = (int) (Math.random() * 6);if (y % 2 == 1) {y = y * (-1);}// 设置旋转角度AffineTransform trans = new AffineTransform();double angle = Math.random() * 0.2;rnd = (int) (Math.random() * 100);if (rnd % 2 == 1) {angle = angle * (-1);}trans.rotate(angle, 4 + i * 16, height / 2);trans.scale(1, 1);g2.setTransform(trans);g2.setFont(new Font("Arial", Font.BOLD, fontSize));g2.setColor(new Color(r, g, b));g2.drawString(ch, 5 + i * 16, 21 + y);}// 释放画笔对象g2.dispose();return bi;}/** * 等比缩放图片 *  * @param bi *            原始图片 * @param maxWidth *            最大宽度 * @param maxHeight *            最大高度 * @return * @throws IOException */public static BufferedImage zoomImage(BufferedImage bi, int maxWidth,int maxHeight) {// 读取原始图片及尺寸int width = bi.getWidth();int height = bi.getHeight();// 计算缩放图片的宽和高// 如果上传的图片均小于等于允许的最大尺寸,则不缩放if (width <= maxWidth && height <= maxHeight) {return bi;}// 计算缩放后的实际宽和高(此时,宽度或高度大于允许的最大尺寸)double scaleW = (double) maxWidth / width;double scaleH = (double) maxHeight / height;double scale = 0;int w = 0;int h = 0;if (scaleW <= scaleH) {scale = scaleW;w = maxWidth;h = (int) (height * scaleW);} else {scale = scaleH;w = (int) (width * scaleH);h = maxHeight;}// 创建缩放后的新图片BufferedImage target = new BufferedImage(w, h, bi.getType());Graphics2D g = target.createGraphics();g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BICUBIC);g.drawRenderedImage(bi,AffineTransform.getScaleInstance(scale, scale));g.dispose();return target;}/** * 剪切图片 *  * @param bi *            图片 * @param x *            起点X * @param y *            起点Y * @param w *            宽度 * @param h *            高度 * @return */public static BufferedImage cutImage(BufferedImage bi, int x, int y,int w, int h) {return bi.getSubimage(x, y, w, h);}}/** * 日期时间工具类 *  * @author duhai *  */public static class DT {/** * 将字符串转成日期时间 *  * @param str *            字符串 * @return */public static Date strToDatetime(String str) {if (Str.isEmpty(str) || !Str.isDatetime(str)) {return null;}String[] arr = str.split("\\s+");String[] ymdArr = arr[0].split("-");String[] hmsArr = arr[1].split(":");Calendar c = new GregorianCalendar(Integer.parseInt(ymdArr[0]),Integer.parseInt(ymdArr[1]) - 1,Integer.parseInt(ymdArr[2]), Integer.parseInt(hmsArr[0]),Integer.parseInt(hmsArr[1]), 0);return new Date(c.getTimeInMillis());}/** * 获取某一日期后经过多少天后的新日期 *  * @param date *            日期 * @param dx *            经过的时间数量 * @return */public static java.sql.Date nextDateAfterDays(java.sql.Date startDate,int dx) {Calendar c = new GregorianCalendar();c.setTime(startDate);c.add(Calendar.DAY_OF_MONTH, dx);java.sql.Date nextDate = new java.sql.Date(c.getTimeInMillis());return nextDate;}/** * 获取某一日期后经过多少月后的新日期 *  * @param date *            日期 * @param dx *            经过的时间数量 * @return */public static java.sql.Date nextDateAfterMonths(java.util.Date startDate, int dx) {Calendar startCalendar = new GregorianCalendar();startCalendar.setTime(startDate);Calendar endCalendar = new GregorianCalendar();endCalendar.setTime(startDate);endCalendar.add(Calendar.MONTH, dx);java.sql.Date nextDate = new java.sql.Date(endCalendar.getTimeInMillis());return nextDate;}/** * 获取某一日期经过多少月后的新日期,时间截止到23:59:59 * @param startDate * @param dx * @return */public static java.util.Date getAutoAfterMonths(java.util.Date startDate, int dx) {Calendar startCalendar = new GregorianCalendar();startCalendar.setTime(startDate);Calendar endCalendar = new GregorianCalendar();endCalendar.setTime(startDate);endCalendar.add(Calendar.MONTH, dx);endCalendar.set(Calendar.HOUR_OF_DAY, 23);endCalendar.set(Calendar.MINUTE, 59);endCalendar.set(Calendar.SECOND, 59);java.sql.Date nextDate = new java.sql.Date(endCalendar.getTimeInMillis());return nextDate;}/** * 获取当月的第一天 * @param startDate * @param dx * @return */public static java.util.Date getFirstCurDays(java.util.Date startDate, int dx) {Calendar startCalendar = new GregorianCalendar();startCalendar.setTime(startDate);Calendar endCalendar = new GregorianCalendar();endCalendar.setTime(startDate);endCalendar.add(Calendar.MONTH, dx);endCalendar.set(Calendar.DAY_OF_MONTH, 1);endCalendar.set(Calendar.HOUR_OF_DAY, 0);endCalendar.set(Calendar.MINUTE, 0);endCalendar.set(Calendar.SECOND, 0);java.sql.Date nextDate = new java.sql.Date(endCalendar.getTimeInMillis());return nextDate;}public static java.util.Date getLastCurDays(java.util.Date startDate, int dx) {Calendar startCalendar = new GregorianCalendar();startCalendar.setTime(startDate);Calendar endCalendar = new GregorianCalendar();endCalendar.setTime(startDate);endCalendar.add(Calendar.MONTH, dx);endCalendar.set(Calendar.DAY_OF_MONTH, endCalendar.getActualMaximum(Calendar.DAY_OF_MONTH));endCalendar.set(Calendar.HOUR_OF_DAY, 23);endCalendar.set(Calendar.MINUTE, 59);endCalendar.set(Calendar.SECOND, 59);java.sql.Date nextDate = new java.sql.Date(endCalendar.getTimeInMillis());return nextDate;}public static void main(String[] args) {System.out.println(formatDatetime(getLastCurDays( new Date(), -1)));}/** * 比较两个日期大小,date1较大时返回1,date2较大时返回-1,相等时返回0 *  * @param date1 * @param date2 * @return */public static int compare(Date date1, Date date2) {long t1 = date1.getTime();long t2 = date2.getTime();if (t1 > t2) {return 1;} else {if (t1 < t2) {return -1;}}return 0;}/** * 将字符串转成日期 *  * @param str *            字符串 * @return */public static java.sql.Date toDate(String str) {String[] ymdArr = str.split("-");Calendar c = new GregorianCalendar(Integer.parseInt(ymdArr[0]),Integer.parseInt(ymdArr[1]) - 1,Integer.parseInt(ymdArr[2]));return new java.sql.Date(c.getTimeInMillis());}/** * 将字符串转成日期时间 *  * @param str *            字符串 * @return */public static Date toDatetime(String str) {String[] arr = str.split("\\s+");String[] ymdArr = arr[0].split("-");String[] hmsArr = arr[1].split(":");Calendar c = new GregorianCalendar(Integer.parseInt(ymdArr[0]),Integer.parseInt(ymdArr[1]) - 1,Integer.parseInt(ymdArr[2]), Integer.parseInt(hmsArr[0]),Integer.parseInt(hmsArr[1]), 0);return new Date(c.getTimeInMillis());}/** * 将一个日期转换为时间字符串 *  * @param d * @return */public static String formatDate(Date d) {if (d == null) {return null;}SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");try {return sdf.format(d);} catch (Exception e) {log.error(e.getMessage());}return null;}/** * 将一个时间月份转换为字符串 * @param d * @return */public static String formatMonth(Date d) {if (d == null) {return null;}SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");try {return sdf.format(d);} catch (Exception e) {log.error(e.getMessage());}return null;}/** * 将一个日期转换为时间字符串 *  * @param d *            日期 * @param format *            格式 * @return */public static String formatDatetime(Date d) {if (d == null) {return null;}SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");try {return sdf.format(d);} catch (Exception e) {log.error(e.getMessage());}return null;}/** * 将一个日期转换为时间字符串 *  * @param d *            日期 * @param format *            格式YYYYMMDDHHMMSS * @return */public static String formatDateYMDHMS(Date d) {if (d == null) {return null;}SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");try {return sdf.format(d);} catch (Exception e) {log.error(e.getMessage());}return null;}public static String getNextYearDateTime() {Calendar cal = Calendar.getInstance();int year = cal.get(Calendar.YEAR) + 1;cal.set(Calendar.YEAR, year);cal.set(Calendar.HOUR_OF_DAY, 23);cal.set(Calendar.MINUTE, 59);cal.set(Calendar.SECOND, 59);Date date = cal.getTime();return formatDatetime(date);}/**      * 计算两个日期之间相差的天数      * @param date1      * @param date2      * @return      */      public static int daysBetween(Date date1,Date date2)      {  java.util.Calendar calst = java.util.Calendar.getInstance();java.util.Calendar caled = java.util.Calendar.getInstance();calst.setTime(date1);caled.setTime(date2);// 设置时间为0时calst.set(java.util.Calendar.HOUR_OF_DAY, 0);calst.set(java.util.Calendar.MINUTE, 0);calst.set(java.util.Calendar.SECOND, 0);caled.set(java.util.Calendar.HOUR_OF_DAY, 0);caled.set(java.util.Calendar.MINUTE, 0);caled.set(java.util.Calendar.SECOND, 0);// 得到两个日期相差的天数int days = ((int) (caled.getTime().getTime() / 1000) - (int) (calst.getTime().getTime() / 1000)) / 3600 / 24;return days;          }          /**     * 计算日期相隔几天的日期     * @param startTime     * @param days     * @return     */    public static Date dateAfterDays(Date startTime, int days)  {    //计算结束时间Calendar cl = Calendar.getInstance();    cl.setTime(startTime);    cl.add(Calendar.DATE, days);    Date endTime = cl.getTime();        return endTime;}}/** * 配置文件工具类 *  * @author duhai *  */public static class PT{public static String getProps(String key) {Properties props = new Properties();try {InputStream in = PT.class.getResourceAsStream(APP_CONFIG);props.load(in);in.close();} catch (Exception e) {e.printStackTrace();}return props.getProperty(key);}public static Properties getProps() {Properties props = new Properties();try {InputStream in = PT.class.getResourceAsStream(APP_CONFIG);props.load(in);in.close();} catch (Exception e) {e.printStackTrace();}return props;}}/** *  * @ClassName: FormatUtil  * @Description: 字符串转类型 * @author duhai  * @date 2017年4月11日 下午4:09:20 */public static class FormatUtil {public static Integer parseInt(String rel) {Integer integer = 0;if (rel != null && !"".equals(rel)) {integer = Integer.parseInt(rel);}return integer;}public static double parseDouble(String rel) {double dou = 0.0;if (rel != null && !"".equals(rel)) {dou = Double.parseDouble(rel);}return dou;}public static Long parseLong(String rel) {Long dou = 0L;if (rel != null && !"".equals(rel)) {dou = Long.parseLong(rel);}return dou;}public static BigDecimal parseBigDecimal(String rel) {BigDecimal dou = new BigDecimal(0);if (rel != null && !"".equals(rel)) { dou = new BigDecimal(rel);}return dou;}/** * 将一个日期转换为时间字符串 *  * @param d * @return */public static String formatDate(Date d) {if (d == null) {return null;}SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");try {return sdf.format(d);} catch (Exception e) {log.error(e.getMessage());}return null;}/** * 将一个日期转换为时间字符串 *  * @param d *            日期 * @param format *            格式 * @return */public static String formatDatetime(Date d) {if (d == null) {return null;}SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");try {return sdf.format(d);} catch (Exception e) {log.error(e.getMessage());}return null;}@SuppressWarnings("finally")public static Date parseDateTime(String rel) {Date datetime = null;try {if (rel != null && !"".equals(rel)) {SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");if (rel.trim().length() == 10) {rel = rel + " 00:00:00";}datetime = simple.parse(rel);}} catch (ParseException e) {e.printStackTrace();} finally {return datetime;}}@SuppressWarnings("finally")public static Date parseTime(String rel) {Date datetime = null;try {if (rel != null && !"".equals(rel)) {SimpleDateFormat simple = new SimpleDateFormat("HH:mm:ss");datetime = simple.parse(rel);}} catch (ParseException e) {e.printStackTrace();} finally {return datetime;}}@SuppressWarnings("finally")public static Date parseDate(String rel) {Date datetime = null;try {if (rel != null && !"".equals(rel)) {SimpleDateFormat simple = null;if (rel.length()>10) {simple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");}else{simple = new SimpleDateFormat("yyyy-MM-dd");}datetime = simple.parse(rel);}} catch (ParseException e) {e.printStackTrace();} finally {return datetime;}}public static java.sql.Date toSqlDate(String str) {if (str == null || "".equals(str)) {return null;}String[] ymdArr = str.split("-");Calendar c = new GregorianCalendar(Integer.parseInt(ymdArr[0]),Integer.parseInt(ymdArr[1]) - 1,Integer.parseInt(ymdArr[2]));return new java.sql.Date(c.getTimeInMillis());}public static Double parseDouble(double d){NumberFormat nf = NumberFormat.getInstance();nf.setMaximumFractionDigits(1);return Double.parseDouble(nf.format(d));}}}

0 0
原创粉丝点击