1. 程式人生 > >專案中常用的Util方法

專案中常用的Util方法

1. 設定幾天前日期

<span style="white-space:pre">	</span>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

<span style="white-space:pre">	</span>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.字串替用

<span style="white-space:pre">	</span>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.比較兩個日期
<span style="white-space:pre">	</span>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 #.##
<span style="white-space:pre">	</span>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 = "[email protected]#_*$-+?<>=";
        String special = "[email protected]_-+?=";
        
        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;
    }
    
}




相關推薦

專案常用Util方法

1. 設定幾天前日期 <span style="white-space:pre"> </span>private Date getDateDynamicDaysAgo(Date startDate, int days) { Calen

專案常用的JavaScript Array(陣列) 物件方法(我是基於Vue2+iView的專案

1、JavaScript splice() 方法 splice() 方法用於新增或刪除陣列中的元素。 注意:這種方法會改變原始陣列,所有主要瀏覽器都支援splice()。 let imgArrItem = [ "/images/201812

專案常用的增刪改方法和查詢方法

增刪改方法: public static int update(String sql,Object...param) { int rowNumber=0; try { PreparedStatement psmt=DBConnection.getConnect

前端開發專案 常用到的 方法(整理)

前端開發專案中 常用到的 方法 1. 獲取URL引數 function getUrlParam(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");

String對象常用方法有哪些?

bsp rec val 字符串長度 方法 end 出現 小寫 轉變 1、length()字符串長度   String str="abc"; System.out.println(str.length()); //輸出3 2、charAt()截取一

String類常用方法(重要)

循環 類型 demo width 尋找 str2 子字符串 replace table 1.字符串與字節 public String(byte[] byte); 將全部字節變成字符串 public String (byte[] byte,int offset,in

測試工作常用方法

期望 action 管理 威脅 人員 rabl 定義 structure 基礎 測試工作中經常用到如下相關方法,主要包括PDCA、SWOT、6W2H、SMART、2/8法則、WBS任務分解法、時間管理。 PDCA循環法則 Plan:制定目標和計劃 Do:按照計

27 string類常用方法列表

nta val nds lsi con valueof 轉換 pan nbsp 1. 獲取方法   int   length()       獲取字符串的長度   char  charAt(int index)    獲取特定位置的字符 (角標越界)   int   

總結Array類型常用方法

包含 enc 對象 參考 http som 對數 fir 負數   Array類型應該是 ECMAScript 中最常用的類型之一了,並且它定義的數組與其他語言有著相當大的區別。數組是數據的有序集合,我們可以通過下標對指定位置的數據進行讀寫;特別的是,在 ECMAScrip

專案常用的讀取配置檔案的方式(一)

package com.bjpowernode.demo01; import java.util.ResourceBundle; /** ResourceBundle讀取配置檔案 @author Administrator */ public clas

專案常用到思科的模組

思科的模組有很多,在專案中經常用到的有以下幾種。一、千兆模組1、千兆單模模組大體樣式如下圖:GLC-LH-SMD:單模10KM模組,工作溫度-5°C to 85°C 。GLC-EX-SMD:單模40KM模組,工作溫度-5°C to 85°C 。GLC-ZX-SMD:單模70KM模組,工作溫度-5°C to 8

JAVA專案常用的異常處理情況總結

1. java.lang.nullpointerexception 這個異常大家肯定都經常遇到,異常的解釋是"程式遇上了空指標",簡單地說就是呼叫了未經初始化的物件或者是不存在的物件,這個錯誤經常出現在建立圖片,呼叫陣列這些操作中,比如圖片未經初始化,或者圖片建立時的路徑錯誤等等。對陣列操作中出現空指標

JAVA專案常用的異常處理情況

1.數學運算異常( java.lang.arithmeticexception) 程式中出現了除以零這樣的運算就會出這樣的異常,對這種異常,大家就要好好檢查一下自己程式中涉及到數學運算的地方,公式是不是有不妥了。 2.陣列下標越界(java.lang.arrayindexoutofboundse

JAVA專案常用的異常知識點總結

JAVA專案中常用的異常知識點總結 1. java.lang.nullpointerexception 這個異常大家肯定都經常遇到,異常的解釋是"程式遇上了空指標",簡單地說就是呼叫了未經初始化的物件或者是不存在的物件,這個錯誤經常出現在建立圖片,呼叫陣列這些操作中,比如圖片未經初始化,或者圖片

正則表示式常用字串方法

1,search()用於檢索字串中指定的子字串,或檢索與正則表示式相匹配的子字串,並返回子串的起始位置。search()方法不支援全域性搜尋,因為會忽略正則表示式引數的標識g,並且也忽略了regexp的lastIndex屬性,總是從字串的開始位置進行檢索,所以它會總是返回str的第一個匹配的位置。 &n

JQ常用方法

1, $().addClass(css中定義的樣式型別) -> 給某個元素新增樣式 $().attr({src:‘test.jpg’,alt:‘test image’}) -> 給某個元素新增屬性/值,引數是map $().attr(‘src’,‘test.jpg’) ->

html及js常用方法(個人總結)

js內建物件 isNaN: 判斷一個元素是不是一個數字(not a number),也就是如果是一個數字返 回None,如果不是一個數字返回True. data物件的方法 getTime 1970-1-1至今的stamp(時間戳) getDate() 獲取時間中的天 getDay

關於String類常用方法

在Java中,常用處理字串的類,在java.lang包中,分別是String和StringBuffer,這兩個類被宣告為final,所以它們沒有子類,不能自定義類來繼承它們。 因為String和StringBuffer類在java.lang包中,所以它們可以自動被所有程式,即使用時不

總結幾個介面常用方法

/** * 構建返回頭資訊 */ private function buildHeader($retCode, $retMessage) { $retNode = new stdClass(); $retNode->retCode = $retCode;

npm包管理工具在一般專案的應用方法

最近自己在有時間,在通學一些知識點,記錄一下,以便以後使用方面 當我們在做專案的時候,如果需要到包管理工具,那麼我們一定會經歷以下流程: 1、首先在官網下載node.js,然後預設安裝到C盤   檢查是否安裝node成功?win+r 輸入cmd開啟命令列,輸入node -v,如果出現版本號則證明安裝成功