项目中常用的Util方法

1. 设置几天前日期

 

private Date getDateDynamicDaysAgo(Date startDate, int days) 
	{
		
		Calendar cal = Calendar.getInstance();
		cal.setTime(startDate);
		cal.add(Calendar.DATE, days);
		Date today30 = cal.getTime();
		
		return today30;
	}

 

 

 

 

 

2.日期差多少天

 

/**
	 * 计算两个日期之间相差的天数
	 * 
	 * @param smdate
	 *            较小的时间
	 * @param bdate
	 *            较大的时间
	 * @return 相差天数
	 * @throws ParseException
	 */
	public static int daysBetween(Date smdate, Date bdate)
			throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		smdate = sdf.parse(sdf.format(smdate));
		bdate = sdf.parse(sdf.format(bdate));
		Calendar cal = Calendar.getInstance();
		cal.setTime(smdate);
		long time1 = cal.getTimeInMillis();
		cal.setTime(bdate);
		long time2 = cal.getTimeInMillis();
		long between_days = (time2 - time1) / (1000 * 3600 * 24);

		return Integer.parseInt(String.valueOf(between_days));
	}

	/**
	 * 字符串的日期格式的计算
	 */
	public static int daysBetween(String smdate, String bdate)
			throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar cal = Calendar.getInstance();
		cal.setTime(sdf.parse(smdate));
		long time1 = cal.getTimeInMillis();
		cal.setTime(sdf.parse(bdate));
		long time2 = cal.getTimeInMillis();
		long between_days = (time2 - time1) / (1000 * 3600 * 24);

		return Integer.parseInt(String.valueOf(between_days));
	}

另一种但没上面效率高

 

369627
daysDiff : 62
369627
daysBetween : 0

 

public static int daysDiff(Date smdate, Date  bdate)throws Exception{
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(smdate);
		int day1 = calendar.get(Calendar.DAY_OF_YEAR);
		int year1 = calendar.get(Calendar.YEAR);
		Calendar calendar2 = Calendar.getInstance();
		calendar2.setTime(bdate);
		int day2 = calendar2.get(Calendar.DAY_OF_YEAR);
		int year2 = calendar2.get(Calendar.YEAR);
		
		int yeardays = 0;
		
		if(year1 < year2){
			for (int year = year1; year < year2; year++) {
				Calendar yearLastDate = Calendar.getInstance();
				yearLastDate.setTime(parseDate(""+year+ "-12-31", "yyyy-MM-dd"));
				yeardays += yearLastDate.get(Calendar.DAY_OF_YEAR);
			}
		}else{
			for (int year = year2; year < year1; year++) {
				Calendar yearLastDate = Calendar.getInstance();
				yearLastDate.setTime(parseDate(""+year+ "-12-31", "yyyy-MM-dd"));
				yeardays += yearLastDate.get(Calendar.DAY_OF_YEAR);
			}
		}
		
		if(year1 < year2){
			yeardays = yeardays * -1;
		}
		return day1 - day2 + yeardays;
	}
	
	public static final Locale DATE_lOCALE = new Locale("en", "US");
	public static final String DATE_PATTERN = "yyyy-MM-dd";
	
	public static Date parseDate(String str) throws Exception{
		Date dt = parseDate(str, DATE_PATTERN);
		return dt;
	}
	public static Date parseDate(String str, String pattern) throws Exception{
		Date dt = parseDate(str, pattern, DATE_lOCALE);
		return dt;
	}
	public static Date parseDate(String str, String pattern, Locale locale) throws Exception{
		Date dt = parseCoreDate(str, pattern, locale);
		return dt;
	}
	
	private static Date parseCoreDate(String str, String pattern, Locale locale) throws Exception{
		Date dt = null;
		try {
			if (StringUtils.isBlank(pattern)) {
				throw new Exception("Error while converting string to date.");
			}
			if (null == locale) {
				throw new Exception("Error while converting string to date.");
			}
			SimpleDateFormat sdf = null;
			sdf = new SimpleDateFormat(pattern, locale);
			sdf.setLenient(false);
			dt = sdf.parse(str);
		} catch (Exception e) {
			throw new Exception("Error while converting string to date.");
		}
		return dt;
		
	}

 

 

 

3.字符串替用

 

ClassLoader classLoader = getClass().getClassLoader();
	String body=StringUtil.read(classLoader, "email/****.tmpl");	
	body = StringUtil.replace(body,
				new String[] {
					"[$TITLE$]", 
					"[$FROM_NAME$]", 
					"[$TO_NAME$]"
				},
				new String[] { 
					subject,
					fromName,
					toName
				});
		
		body = StringUtil.replace(body,"[$CONTENT$]",content);

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>[$TITLE$]</title>        
	</head>
	<body>
    	Dear [$TO_NAME$],
    	
		<br /><br />
		[$CONTENT$]
		<br /><br />
	
	</body>
</html>

 

 

 

 

 

4.星期几的Util

 

import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;

public class WeekDayUtil {
	
	public enum WeekDays {
		Day1(1,"Day 1"),  //0b0000001
		Day2(2,"Day 2"),  //0b0000010
		Day3(4,"Day 3"),  //0b0000100
		Day4(8,"Day 4"),  //0b0001000
		Day5(16,"Day 5"), //0b0010000
		Day6(32,"Day 6"), //0b0100000
		Day7(64,"Day 7"); //0b1000000
		
		private int value;
		private String name;
		
		WeekDays(int val, String nam) {
			value = val;
			name = nam;
		}
		
		public int getValue() {
			return value;
		}
		
		public String getName() {
			return name;
		}
	}
	
	public static int encodeList(List<WeekDays> set) {
	    int ret = 0;
	    
	    for (WeekDays val : set) {
	        ret |= 1 << val.ordinal();
	    }
	    
	    return ret;
	}
	
	public static List<WeekDays> decodeToList(int encoded) {
		List<WeekDays> ret = new ArrayList<WeekDays>();
		
		for (WeekDays val : EnumSet.allOf(WeekDays.class)) {
			if((encoded & val.getValue()) != 0) {
				ret.add(val);
			}
		}
		return ret;
	}
	
	public static boolean isDaySelected(int value, WeekDays d) {
		boolean match = false;
		
		if((value & d.getValue()) != 0) { match = true; }
		
		return match;
	}
}


5.load property file to Json Object

 

 

<span style="white-space:pre">	</span>//method to convert property file to JSON object
	public static String convertPropertiesFileToJSONString(Properties pro ){
		String itemsJSON = "";
		Object[] keySet = pro.keySet().toArray();
	
		//System.out.println(keySet.length);
		
		
		for (Object key:keySet) {
			//System.out.println(key);
			itemsJSON += ",'" +key.toString() + "':'"+  pro.getProperty((String)key) + "'";
		}
		
		if (!itemsJSON.isEmpty())
			itemsJSON = itemsJSON.substring(1);
		
		itemsJSON ="{" + itemsJSON +  "}";

		_log.info(itemsJSON);
		
		return itemsJSON;
	}


6.比较两个日期

 

 

public static int compareDate(Date date1, Date date2) {
		if (date1.getYear()>date2.getYear())
			return 1;
		else if (date1.getYear() <date2.getYear())
			return -1;
		else if (date1.getMonth() >date2.getMonth())
			return 1;
		else if (date1.getMonth() <date2.getMonth())
			return -1;
		if (date1.getDate()>date2.getDate())
			return 1;
		else if (date1.getDate() <date2.getDate())
			return -1;
		return 0;
	}


7.计算年龄

 

 

	public static int calculateAge(Date birthday) {
		int age = 0;

		if (birthday != null) {
			Calendar dob = Calendar.getInstance();
			Calendar today = Calendar.getInstance();

			dob.setTime(birthday);
			age = today.get(Calendar.YEAR) - dob.get(Calendar.YEAR);

			if (today.get(Calendar.DAY_OF_YEAR) <= 
					dob.get(Calendar.DAY_OF_YEAR)) {
				age--;
			}
		}

		return age;
	}


8.Format Double to #.##

 

 

public static double formatDoubleValue(double value){
		DecimalFormat twoDForm = new DecimalFormat("#.##");
	    return Double.valueOf(twoDForm.format(value));
	}


9,限制图片格式

 

 

 public static boolean isStrickImage(UploadedFile imageFile) {
        if (imageFile == null)
            return false;

        String contentType = imageFile.getContentType().toLowerCase();

        boolean isImage = false;
        if (contentType.contains("gif")) {
            isImage = strickModeImage(imageFile, "gif");
        } else if (contentType.contains("png")) {
            isImage = strickModeImage(imageFile, "png");
        } else if (contentType.contains("bmp")) {
            isImage = strickModeImage(imageFile, "bmp");
        } else if (contentType.contains("jpg")) {
            isImage = strickModeImage(imageFile, "jpg");
        } else if (contentType.contains("jpeg")) {
            isImage = strickModeImage(imageFile, "jpeg");
        }

        return isImage;
    }

    private static boolean strickModeImage(UploadedFile imageFile,
                                           String imageType) {
        if (imageFile == null || imageType == null) {
            return false;
        }
        InputStream is = null;
        try {
            imageType = imageType.toLowerCase();
            is = imageFile.getInputStream();
            String beginStr = null;
            if (imageType.equals("jpg") || imageType.equals("jpeg")) {
                beginStr = "FFD8FF";
            } else if (imageType.equals("png")) {
                beginStr = "89504E47";
            } else if (imageType.equals("gif")) {
                beginStr = "47494638";

            } else if (imageType.equals("bmp")) {
                beginStr = "424D";
            }

            if (beginStr == null) {
                return false;
            }


            byte[] b = new byte[beginStr.length() / 2];
            is.read(b, 0, b.length);
            String headStr = bytesToHexString(b);
            if (beginStr.equals(headStr)) {
                return true;
            } else {
                return false;
            }


        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                is.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

 

 

 

 

 

10.String 操作

 

    public static boolean containsOnlyNumbers(String str) {
        // it can't contain only numbers if it's null or empty...
        if (str == null || str.length() == 0) {
            return false;
        }

        for (int i = 0; i < str.length(); i++) {
            // if we find a non-digit character we return false.
            if (!Character.isDigit(str.charAt(i)))
                return false;
        }

        return true;
    }
    
    public static boolean checkPostalCode(String postal) {
        Pattern pattern = Pattern.compile("\\d{1,6}");
        Matcher matcher = pattern.matcher(postal);
        if (!matcher.matches())
            return false;
        else
            return true;
    }
    public static boolean checkMobileNo(String mobileNo) {
        if(isEmpty(mobileNo)){
            return true;
        }
        Pattern pattern = Pattern.compile("[0-9]{1,12}");
        Matcher matcher = pattern.matcher(mobileNo);
        if (matcher.matches())
            return false;
        else
            return true;
    }


11.password 生成

 

 

public class PasswordUtil {
    public PasswordUtil() {
        super();
    }
    
    
    private static final Logger logger = LoggerFactory.getLogger(PasswordUtil.class);
    
    
    // generate 8 characters random password...
    public static String newPassword(){
        
        String password = "";
        String alphaUp = "abcdefghijklmnopqrstuvwxyz";
        String alphaLow = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String numeric = "0987654321";
        //String special = "!@#_*$-+?<>=";
        String special = "!@_-+?=";
        
        password += RandomStringUtils.random(2,alphaUp);
        password += RandomStringUtils.random(2,numeric);
        password += RandomStringUtils.random(2,special);
        password += RandomStringUtils.random(2,alphaLow);
        
        List<Character> characters = new ArrayList<Character>();  
        for(char c : password.toCharArray()) {  
            characters.add(c);  
        }  
        Collections.shuffle(characters);  
        StringBuilder sb = new StringBuilder();  
        for(char c : characters) {  
            sb.append(c);  
        }  
        
        password = sb.toString();
        return password;
    }
    
    public static boolean validatePassword(String password){
        
        
        boolean result = true;
        
        //1.) must be at least 8 characters
        if(password.length() < 8){
            logger.info("Length of password is "+password.length()+" which is less than 8");
            return false;
        }
        //2.) must have at least one numeric character
        if(!password.matches(".*\\d.*")){
            logger.info("Password does not contain any numeric character");
            return false;
        }
        
        // check for alphabet also?
        
        //3.) must have at least one numeric character
        if(!password.matches(".*?\\p{Punct}.*")){
            logger.info("Password does not contain any special character");
            return false;
        }
        
        //4.) must have at least one lowercase character
        if(!password.matches(".*[a-z].*")){
            logger.info("Password does not contain lowercase character");
            return false;
        }
        return result;
    }
    
}

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值