java常用计算方法

package com.helpUtil;

import java.util.*;
import java.text.SimpleDateFormat;
import java.security.*;
import org.apache.commons.lang.StringUtils;
import java.math.BigDecimal;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.Calendar;

/**
* 通用的一些辅助功能
* @author Administrator
*
*/
public class HelpUtil {
public HelpUtil() {
super();
}

    private static final String SPLITTER=",";

    /**
     * 在字符串后填充空格
     * @param instr
     * @param wd
     * @return
     */
   
    public static String retWidthString(String instr,int wd){
    String ret=instr;
    while(instr.length()<wd){
    wd--;
    ret+=" ";
    }
    return ret;
    }
   
    public static String addTimeToStr(String oldstr){
        SimpleDateFormat dateFormat =new SimpleDateFormat("yyMMddHHmmss");
        return "("+dateFormat.format(new Date())+")"+oldstr.trim();
    }


/** 字符串时间的加减 : 字符串时间,加减量,加减的类型<年、月、日>,加减的动作<加/减> */
public Calendar DateOperation(String dateString, int number, String type,
Boolean flag) {
try {
Calendar calendar = Calendar.getInstance();
calendar.setTime(DateFormat.getDateInstance().parse(dateString));
if (type.equals("DATE")) {
if (flag == true)
number = calendar.get(Calendar.DATE) + number;
else
number = calendar.get(Calendar.DATE) - number;
calendar.set(Calendar.DATE, number);
} else if (type.equals("MONTH")) {
if (flag == true)
number = calendar.get(Calendar.MONTH) + number;
else
number = calendar.get(Calendar.MONTH) - number;
calendar.set(Calendar.MONTH, number);
} else {
if (flag == true)
number = calendar.get(Calendar.YEAR) + number;
else
number = calendar.get(Calendar.YEAR) - number;
calendar.set(Calendar.YEAR, number);
}
return calendar;
} catch (ParseException e) {
System.err
.println("DataUtil : DateOperation : ParseException : 字符串时间格式不对 !例如 : \"2006-12-05\""
+ e.getMessage());
}
return null;
}

/** 测试字符串时间范围 :开始时间,结束时间,需要比较时间, return 0 = 在此范围内,1 = 大于结束时间,-1 = 小于开始时间, -2 = 异常 */
public static int compareToDate(String start, String end, String source) {
if(HelpUtil.compareTo(start,end) < 0)
return -2;
int i = HelpUtil.compareTo(start, source);
int j = HelpUtil.compareTo(end, source);
if (i == -2 || j == -2)
return -2;
else if (i >= 0 && j <= 0)
return 0;
else if (j > 0)
return 1;
else
return -1;
}

/** 比较两个字符串时间的大小 : 基准时间,需要比较时间, return 1 = 大于; -1 = 小于; 0 = 等于; -2 = 异常 */
public static int compareTo(String benchmarkDate, String sourceDate) {
try {
Calendar benchmark = Calendar.getInstance();
benchmark
.setTime(DateFormat.getDateInstance().parse(benchmarkDate));
Calendar source = Calendar.getInstance();
source.setTime(DateFormat.getDateInstance().parse(sourceDate));
int i = source.compareTo(benchmark);
if (i > 0)
return 1;
else if (i < 0)
return -1;
else
return i;
} catch (ParseException e) {
System.err
.println("DataUtil : compareTo : ParseException : 字符串时间格式不对 !例如 : \"2006-12-05\""
+ e.getMessage());
return -2;
}
}


   
    /**
     * 判断 myDate 是否在给定的日期期间(格式:YYYY-MM-DD)
     * @param myDate
     * @param startDate
     * @param endDate
     * @return
     */
    public static boolean isDateInRange(String myDate,String startDate,String endDate){
        if(myDate==null) return false;
    myDate=myDate.replaceAll("-","");
    startDate=startDate.replaceAll("-","");
    endDate=endDate.replaceAll("-","");
        boolean inRange=false;
        if (Double.parseDouble(myDate)<=Double.parseDouble(endDate)&&
            Double.parseDouble(myDate) >=Double.parseDouble(startDate)){
          inRange = true;

      }
      return inRange;
    }
    /**
     * 去除数组中相同的元素 使它为null (注意:调用时要判断,避免出现null异常)
     * @param str String[]
     * @return String[]
     */
    @Deprecated
    public static  String[] arrange(String[] str ){
      for(int i=0;i<str.length;i++){
          for(int j=i+1;j<str.length;j++){
              if(str[i].equals(str[j])){
                  str[i]=null;
                  break;
          }
          }
      }
      return str;
}
/**
* 将str1,str2,str3,形式转化为list
* @param department
* @return
*/
public static List parse(String department){
java.lang.String str=department;
int length=str.lastIndexOf(SPLITTER);
str=str.substring(0,length);
String[] strs=str.split(SPLITTER);
List deptList=new ArrayList();
for(int i=0;i<strs.length;i++){
deptList.add(strs[i]);
}
return deptList;
}

        /**
         * 将str1,str2,str3  形式转化为list
         * @param department
         * @return
         */
        public static List parsenomore(String department){
            List deptList=new ArrayList();
            if(!StringUtils.isEmpty(department)){
                java.lang.String str = department;
                String[] strs = str.split(SPLITTER);
                for (int i = 0; i < strs.length; i++) {
                    deptList.add(strs[i]);
                }
            }
            return deptList;
        }

        /**
         * if trg in src,return true, src is: 2,4,3,5,6,12,11  trg is: 1
         * @param department
         * @return
         */
        public static boolean seekStr(String src,String trg){
        boolean ret=false;
            if(!StringUtils.isEmpty(src)){
                String[] strs = src.split(SPLITTER);
                for (int i = 0; i < strs.length; i++) {
                if(strs[i].equals(trg)){
                ret=true;
                break;
                }
                }
            }
            return ret;
        }


        /**
         * 查找两个字符串中是否有一个元素相同
         * @param s1  2,3,4,55,67
         * @param s2  3,5,32
         * @return
         */
        public static boolean seekTwoStr(String s1,String s2){
        boolean ret=false;
       
            if(!StringUtils.isEmpty(s1) && !StringUtils.isEmpty(s2)){
                String[] ss1 = s1.split(SPLITTER);
                String[] ss2 = s2.split(SPLITTER);
               
                for(int i=0;i<ss1.length;i++)
                for(int j=0;j<ss2.length;j++)
                if(ss1[i].equals(ss2[j])){
                ret=true;
                break;
                }
            }
            return ret;
        }
       
       
        /**
         * 把2|3|4|5|6 转换为list
         * @param department
         * @return
         */
        public static List parseSplit(String st){
            List deptList=new ArrayList();
            if(!StringUtils.isEmpty(st)){
            while(st.indexOf("|")>0){
            deptList.add(st.substring(0,st.indexOf("|")));
            st=st.substring(st.indexOf("|")+1);
            }
            deptList.add(st);
            }
            return deptList;
        }

        /**
         * 把2,3,4,5,6 转换为list
         * @param department
         * @return
         */
        public static List parseSplitDoc(String st){
            List deptList=new ArrayList();
            if(!StringUtils.isEmpty(st)){
            while(st.indexOf(",")>0){
            deptList.add(st.substring(0,st.indexOf(",")));
            st=st.substring(st.indexOf(",")+1);
            }
            deptList.add(st);
            }
            return deptList;
        }
/**
* 将str1,str2,str3,形式转化为set
* @param idno
* @param idnos
* @return
*/
public static Set parseIntoSet(Set idno,String idnos){
            if(StringUtils.isNotBlank(idnos)){
                java.lang.String str = idnos;
               // System.out.println("idnos="+idnos);
                int length = str.lastIndexOf(SPLITTER);

                //System.out.println("length="+length);
                if(length!=-1){
                    str = str.substring(0, length);
                }
                String[] strs = str.split(SPLITTER);

                for (int i = 0; i < strs.length; i++) {
                    idno.add(strs[i]);
                }
            }
            return idno;
}

/**
* 将str1,str2,str3形式转化为set
* @param idno
* @param idnos
* @return
*/
public static Set parseIntoSet(String idnos){
    Set idno=new HashSet();
   
            if(StringUtils.isNotBlank(idnos)){
                java.lang.String str = idnos;
                String[] strs = str.split(SPLITTER);

                for (int i = 0; i < strs.length; i++) {
                    idno.add(strs[i]);
                }
            }
            return idno;
}


/**
* 将list形式转化为str1,str2,str3
* @param deptList
* @return
*/
public static String assemble(List deptList){
StringBuffer strBuf=new StringBuffer();
for (int i=0;i<deptList.size()-1;i++){
strBuf.append(deptList.get(i)).append(SPLITTER);
}
strBuf.append(deptList.get(deptList.size()-1));
return strBuf.toString();
}

        /**
         * 返回日期格式
         * @return String
         */
        public static String retformatdate(String s) throws Exception{
            SimpleDateFormat dateFormat =new SimpleDateFormat("yyyy-MM-dd");
            Date d=dateFormat.parse(s);
            return dateFormat.format(d);
        }

        /**
         * 返回系统当前日期
         * @return String
         */
        public static String getNowTime(){
            SimpleDateFormat dateFormat =new SimpleDateFormat("yyyy-MM-dd");
            return dateFormat.format(new Date());
        }
       
        //返回前n天日期
        public static String getNowTimeBefore(int days){
        Calendar data = new GregorianCalendar();
    int day = data.get(Calendar.DATE);
    day = day - days;
    data.set(Calendar.DAY_OF_MONTH, day);
            return data.get(Calendar.YEAR) + "-"+ (data.get(Calendar.MONTH) + 1) + "-"+ data.get(Calendar.DATE);
        }

        /**
         * 返回本月第一天
         * @return
         */
        public static String getTheFirstDateOfThisMonth(){
        int years=Calendar.getInstance().get(Calendar.YEAR);
        int months=Calendar.getInstance().get(Calendar.MONTH)+1;
        return String.valueOf(years)+"-"+String.valueOf(months)+"-01";
        }
       
        /**
         * 返回系统当前时间
         * @return String
         */
        public static String getTime(){
            SimpleDateFormat dateFormat =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return dateFormat.format(new Date());
        }
       
        /**
         * 返回系统当前时间
         * @return String
         */
        public static String getTimeNoHour(){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return dateFormat.format(new Date());
        }
        /**
         * Used by the hash method.
         */
        private static MessageDigest digest = null;

        /**
         * 加密
         *
         * @param data the String to compute the hash of.
         * @return a hashed version of the passed-in String
         */
        public synchronized static final String hash(String data) {
            if (digest == null) {
                try {
                    digest = MessageDigest.getInstance("MD5");
                }
                catch (NoSuchAlgorithmException nsae) {
                    System.err.println("Failed to load the MD5 MessageDigest. " +
                    "Jive will be unable to function normally.");
                    nsae.printStackTrace();
                }
            }
            // Now, compute hash.
            digest.update(data.getBytes());
            return encodeHex(digest.digest());
        }

        /**
         * 组合成字符串
         *
         * @param bytes an array of bytes to convert to a hex-string
         * @return generated hex string
         */
        public static final String encodeHex(byte[] bytes) {
            StringBuffer buf = new StringBuffer(bytes.length * 2);
            int i;

            for (i = 0; i < bytes.length; i++) {
                if (((int) bytes[i] & 0xff) < 0x10) {
                    buf.append("0");
                }
                buf.append(Long.toString((int) bytes[i] & 0xff, 16));
            }
            return buf.toString();
        }

        /**
         * convert from String[] to str,str,str
         * @param str String[]
         * @return String
         */
        public static String arrayToString(String[] str){
            String temp=null;
            if(str!=null)
            for(int i=0;i<str.length;i++){
                if(temp!=null)
                    temp=temp+","+str[i];
                else
                    temp=str[i];
            }
            return temp;
        }
        /**
         * convert from String[] to str,str,str
         * @param str String[]
         * @return String
         */
        public static String arrayToStringf(String[] str){
            String temp=null;
            if(str!=null)
            for(int i=0;i<str.length;i++){
                if(temp!=null)
                    temp=temp+";"+str[i];
                else
                    temp=str[i];
            }
            return temp;
        }

        /**
         * 把double 数按规定的小数位数四舍五入输出
         *
         * @param dSource
         * @param len
         * @return
         */
        public static double getRound(double dSource,int len){
        double iRound;
        //BigDecimal的构造函数参数类型是double
        BigDecimal deSource = new BigDecimal(dSource);
        //deSource.setScale(0,BigDecimal.ROUND_HALF_UP) 返回值类型 BigDecimal
        //intValue() 方法将BigDecimal转化为int
        iRound= deSource.setScale(len,BigDecimal.ROUND_HALF_UP).doubleValue();
        return iRound;
        }
        /**
         * 把double 数按规定的小数位数四舍五入输出
         * add by tony * this method is not a good method *
         * @param dSource
         * @param len
         * @return
         */
    public static double formatDou(double doubleint){
//    DecimalFormat de = new DecimalFormat("#.00");
//    return Double.parseDouble(de.format(doubleint));
      double iRound;
          //BigDecimal的构造函数参数类型是double
          BigDecimal deSource = new BigDecimal(Double.toString(doubleint));
          //deSource.setScale(0,BigDecimal.ROUND_HALF_UP) 返回值类型 BigDecimal
          //intValue() 方法将BigDecimal转化为int
          iRound= deSource.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
          return iRound;
    }
       
   
    public String getStautColor(int stat){
    String color="";
    if(stat==0){
    color="<img src='image/nobusy.jpg' width='30' height='15'>";
    }
    if(stat==1){
    color="<img src='image/busy.jpg' width='30' height='15'  onclick=\"showTask(param)\" style='cursor:hand'>";
    }
    if(stat==2){
    color="<img src='image/rest.jpg' width='30' height='15'>";
    }
    if(stat==3){
    color="<img src='image/rest2.jpg' width='30' height='15'>";
    }
    return color;
    }
   
       


   
    /**
    * 把0、1变为是否
    * @param bool
    * @return
    */
    public static String getBoolean(int bool){
    String mess="否";
    if(bool==1){
    mess="是";
    }
    if(bool==0){
    return mess;
    }
    return mess;
    }
   
    public static String getQAKind(int kind){
    String mess="";
    switch(kind){
    case 1:
    mess="checklist";break;
    case 0:
    mess="评分问卷";break;
    }
    return mess;
    }      


    /**
    * 参数:sYear年,sMonth月
    * 返回值:String 该年月的 第一天
    */
    public static String getFirstDateInTheMonth(int sYear,int sMonth){
    return sYear+"-"+sMonth+"-"+"01";
    }
       
    /**
    * @param sYear年
    * @param sMonth月
    * @returnString 该年月的 最后一天
    */
    public static String getLastDateInTheMonth(int sYear,int sMonth){
    Calendar calendar=Calendar.getInstance();
    calendar.set(sYear,sMonth,0);
    return sYear+"-"+sMonth+"-"+String.valueOf(calendar.get(calendar.DAY_OF_MONTH));
    }
   

    /**
    * 参数:sYear年,sMonth月
    * 返回值:String 该年月的 第一天
    */
    public static String getFirstDateInTheMonthWithSecond(int sYear,int sMonth){
    return sYear+"-"+sMonth+"-"+"01 00:00:00";
    }
       
    /**
    * @param sYear年
    * @param sMonth月
    * @returnString 该年月的 最后一天
    */
    public static String getLastDateInTheMonthWithSecond(int sYear,int sMonth){
    Calendar calendar=Calendar.getInstance();
    calendar.set(sYear,sMonth,0);
    return sYear+"-"+sMonth+"-"+String.valueOf(calendar.get(calendar.DAY_OF_MONTH))+" 23:59:59";
    }
   
    

         
       
       
        /**返回上一个idno或下一个idno
         * @param idnostr idno 的字符串集合 如:,1,2,3,4
         * @param curridno 当前记录的idn
         * @param flag 0下一个记录;>0上一个记录
         * @return 目标idno字符串
         */
        public static String GetPriOrNextRecord(String idnostr,String curridno,int flag){
        String recid=null;
        int pos1;
        List idnoC=parsenomore(idnostr);
    int lang=idnoC.size();
        pos1=idnoC.indexOf(curridno);
    if(pos1!=0&&flag>0)
    recid=(String)idnoC.get(pos1-1);   
    else if(pos1!=lang-1&&flag==0)  
    recid=(String)idnoC.get(pos1+1);
    else{
    recid="";
    }
        return null;
        }   
       
       
        /**
         *
         * @param time YYYY-MM-DD HH:mm:ss
         * @return时间的string数组 string[i] i:0 年、 1 月、 2 日 、3 秒
         */
        public static String[] getTimeArray(String time){
        String datetime[]=new String[4];
        StringTokenizer timelist=new StringTokenizer(time," :");
        int i=0;
        while(timelist.hasMoreTokens()){
        datetime[i]=timelist.nextToken();
        i++;   
        }
        return datetime;
        }
       
        /**
         * @param time 类型string[4] i:0 年、 1 月、 2 日 、3 秒
         * @return 返回时间字符串格式为:YYYY-MM-DD HH:mm:ss
         */
        public static String getTimeStr(String[] time){
        String datetime;
        datetime=time[0]+" "+time[1]+":"+time[2]+":"+time[3];  
        return datetime;
        }
       
        public static String getStateStr(int stat){
    String str="";
    if(stat!=1){
    str="&nbsp;";
    }
    if(stat==1){
    str="<span style='color:#FF0000'>BUSY</span>";
    }
    //if(stat==2){
    // color="<img src='image/rest.jpg' width='30' height='15'>";
    //}
    return str;
        }

        /** 当前时间 - 给定的时间 = ? 年 ?月?日 */
        public static String countTime(String dateString) {
        if (dateString != null) {
        try {
        Calendar old = Calendar.getInstance();
        old.setTime(DateFormat.getDateInstance().parse(dateString));
        Calendar now = Calendar.getInstance();
        StringBuilder time = new StringBuilder();
        int year = 0, month = 0, date = 0, m = 0, y = 0;
        if (now.after(old)) {
        year = now.get(Calendar.YEAR) - old.get(Calendar.YEAR);
        month = now.get(Calendar.MONTH) - old.get(Calendar.MONTH);
        date = now.get(Calendar.DATE) - old.get(Calendar.DATE);
        m = old.get(Calendar.MONTH) + 1;
        y = old.get(Calendar.YEAR);
        } else {
        time.append("-");
        year = old.get(Calendar.YEAR) - now.get(Calendar.YEAR);
        month = old.get(Calendar.MONTH) - now.get(Calendar.MONTH);
        date = old.get(Calendar.DATE) - now.get(Calendar.DATE);
        m = now.get(Calendar.MONTH) + 1;
        y = now.get(Calendar.YEAR);
        }
        if (date < 0) {
        if (m == 1 || m == 3 || m == 5 || m == 7 || m == 8
        || m == 10 || m == 12)
        date += 31;
        else if (m == 2) {
        if (y % 400 == 0 || (y % 4 == 0 && y % 100 != 0))
        date += 29;
        else
        date += 28;
        } else
        date += 30;
        month--;
        }
        if (month < 0) {
        month += 12;
        year--;
        }
        if(year>0) time.append(year + "年");
        if(month>0) time.append(month + "月");
        if(date>0) time.append(date + "天");
        return time.toString();
        } catch (ParseException e) {
        System.err
        .println("DataUtil : countYear : ParseException : 字符串时间格式不对 !例如 : \"2006-12-05\""
        + e.getMessage());
        }
        }
        return null;
        }       
       
        /*对数组的值从小到大排序*/
        public static int[] doArray(int[] a,int type){
            Arrays.sort(a);
            if(type==1)
                return a;
            else if(type==2){
                for (int i=0;i<a.length;i++){
                    for (int j=i+1;j<a.length;j++){
                        if(a[i]<a[j]){
                            int t=0;
                            t=a[i];
                            a[i]=a[j];
                            a[j]=t;
                        }
                    }
                }
            }
            return a;
        }
        /**
         * 返回系统当前时间
         * @return String
         */
        public static String getCurrnetYear(){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");
        return dateFormat.format(new Date());
        }
        /**
         * 返回系统当前时间
         * @return String
         */
        public static String getNeedDate(String strDate,int nCount){
        GregorianCalendar worldTour
        = new GregorianCalendar(Integer.parseInt(strDate.substring(0,4)),
        Integer.parseInt(strDate.substring(5,7))-1,
        Integer.parseInt(strDate.substring(8)));
        worldTour.add(GregorianCalendar.DATE, -nCount);
        Date d = worldTour.getTime();
        SimpleDateFormat df=new SimpleDateFormat ("yyyy-MM-dd");
        return df.format(d);
            }
public static long getDayBetween(String startDate,String endDate)
   {
   long DAY = 24L * 60L * 60L * 1000L;   
   SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd" ); 
   Date d1=null;
   Date d2 = null;
   try{
   d1 = df.parse(startDate);   
   d2 = df.parse(endDate);  
    
   }catch(Exception e){
   e.printStackTrace();
   }
   return (d2.getTime() - d1.getTime())/DAY; 
     
   }
}

你可能感兴趣的:(java,apache,Security,J#)