Java工具类六 -- 其它类型

1.字段验证工具类

对字段进行判断的工具,每个项目必备吧,简单总结了一下,有优化的,或者更多的请提出,可以不断完善。

[java]  view plain copy
  1. import java.util.regex.Matcher;  
  2. import java.util.regex.Pattern;  
  3.   
  4. /** 
  5.  * 字段验证工具 
  6.  * @author lixinglei 
  7.  * 
  8.  */  
  9. public class ValidatorUtil {  
  10.       
  11.     /** 
  12.      * 判断是否为浮点数或者整数 
  13.      * @param str 
  14.      * @return true Or false 
  15.      */  
  16.     public static boolean isNumeric(String str){  
  17.           Pattern pattern = Pattern.compile("^(-?\\d+)(\\.\\d+)?$");  
  18.           Matcher isNum = pattern.matcher(str);  
  19.           if( !isNum.matches() ){  
  20.                 return false;  
  21.           }  
  22.           return true;  
  23.     }  
  24.       
  25.     /** 
  26.      * 判断是否为正确的邮件格式 
  27.      * @param str 
  28.      * @return boolean 
  29.      */  
  30.     public static boolean isEmail(String str){  
  31.         if(isEmpty(str))  
  32.             return false;  
  33.         return str.matches("^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$");  
  34.     }  
  35.       
  36.     /** 
  37.      * 判断字符串是否为合法手机号 11位 13 14 15 18开头 
  38.      * @param str 
  39.      * @return boolean 
  40.      */  
  41.     public static boolean isMobile(String str){  
  42.         if(isEmpty(str))  
  43.             return false;  
  44.         return str.matches("^(13|14|15|18)\\d{9}$");  
  45.     }  
  46.       
  47.     /** 
  48.      * 判断是否为数字 
  49.      * @param str 
  50.      * @return 
  51.      */  
  52.     public static boolean isNumber(String str) {  
  53.         try{  
  54.             Integer.parseInt(str);  
  55.             return true;  
  56.         }catch(Exception ex){  
  57.             return false;  
  58.         }  
  59.     }  
  60.       
  61.           
  62.     /** 
  63.      * 判断字符串是否为非空(包含null与"") 
  64.      * @param str 
  65.      * @return 
  66.      */  
  67.     public static boolean isNotEmpty(String str){  
  68.         if(str == null || "".equals(str))  
  69.             return false;  
  70.         return true;  
  71.     }  
  72.       
  73.     /** 
  74.      * 判断字符串是否为非空(包含null与"","    ") 
  75.      * @param str 
  76.      * @return 
  77.      */  
  78.     public static boolean isNotEmptyIgnoreBlank(String str){  
  79.         if(str == null || "".equals(str) || "".equals(str.trim()))  
  80.             return false;  
  81.         return true;  
  82.     }  
  83.       
  84.     /** 
  85.      * 判断字符串是否为空(包含null与"") 
  86.      * @param str 
  87.      * @return 
  88.      */  
  89.     public static boolean isEmpty(String str){  
  90.         if(str == null || "".equals(str))  
  91.             return true;  
  92.         return false;  
  93.     }  
  94.       
  95.     /** 
  96.      * 判断字符串是否为空(包含null与"","    ") 
  97.      * @param str 
  98.      * @return 
  99.      */  
  100.     public static boolean isEmptyIgnoreBlank(String str){  
  101.         if(str == null || "".equals(str) || "".equals(str.trim()))  
  102.             return true;  
  103.         return false;  
  104.     }  
  105.       
  106.       
  107.     //禁止实例化  
  108.     private ValidatorUtil(){}   
  109. }  

2.人民币大写金额转换


在项目开发过程中偶尔会遇到需要把人民币金额由数字转换成大写金额的形式,例如,将“123456”转换成“壹拾贰万叁千肆百伍拾陆”这样子,这种情况在程序需要打印一些单据时会普遍用到,而下面一个程序就解决了这个问题,如果大家觉得有用,请一定帮我顶起来啊^-^,另外,希望各网友也将自己的类似的处理程序拿出来分享。

  1. import java.text.DecimalFormat;
  2. import java.text.NumberFormat;
  3. //总体思路:
  4. //对数字进行分级处理,级长为4
  5. //对分级后的每级分别处理,处理后得到字符串相连
  6. //如:123456=12|3456
  7. //第二级:12=壹拾贰 + “万”
  8. //第一级:3456 =叁千肆百伍拾陆 + “”
  9. public final class RMB {
  10.   private double amount = 0.0D;
  11.   private static final String NUM = "零壹贰叁肆伍陆柒捌玖";
  12.   private static final String UNIT = "仟佰拾个";
  13.   private static final String GRADEUNIT = "仟万亿兆";
  14.   private static final String DOTUNIT = "角分厘";
  15.   private static final int GRADE = 4;
  16.   private static final String SIGN = "¥";
  17.   private static final NumberFormat nf = new DecimalFormat("#0.###");
  18.   public RMB(double amount) {
  19.     this.amount = amount;
  20.   }
  21.   public String toBigAmt(){
  22.     return toBigAmt(this.amount);
  23.   }
  24.   public static String toBigAmt(double amount){
  25.     String amt = nf.format(amount);
  26.     Double d = new Double(amount);
  27.     String dotPart = ""//取小数位
  28.     String intPart = ""//取整数位
  29.     int dotPos;
  30.     if ( (dotPos = amt.indexOf('.')) != -1) {
  31.       intPart = amt.substring(0, dotPos);
  32.       dotPart = amt.substring(dotPos + 1);
  33.     }
  34.     else {
  35.       intPart = amt;
  36.     }
  37.     if(intPart.length() > 16throw new java.lang.InternalError("The amount is too big.");
  38.     String intBig = intToBig(intPart);
  39.     String dotBig = dotToBig(dotPart);
  40.     //以下代码稍做修改,现在是完美的代码啦!
  41.     if ((dotBig.length() == 0)&&(intBig.length() != 0)) {
  42.       return intBig + "元整";
  43.     }else if((dotBig.length() == 0)&&(intBig.length() == 0)){
  44.       return intBig + "零元";  
  45.     }else if((dotBig.length() != 0)&&(intBig.length() != 0)) {
  46.       return intBig + "元" + dotBig;
  47.     }else{
  48.       return dotBig;  
  49.     }
  50. /*
  51.     if(dotBig.length() == 0) return intBig +"元整";
  52.     else return intBig + "元" + dotBig;
  53. */
  54.   }
  55.   private static String dotToBig(String dotPart){
  56.       //得到转换后的大写(小数部分)
  57.     String strRet = "";
  58.     for(int i=0; i<dotPart.length() && i<3; i++){
  59.       int num;
  60.       if((num = Integer.parseInt(dotPart.substring(i,i+1))) != 0)
  61.         strRet += NUM.substring(num,num+1) + DOTUNIT.substring(i,i+1);
  62.     }
  63.     return strRet;
  64.   }
  65.   private static String intToBig(String intPart){
  66.       //得到转换后的大写(整数部分)
  67.       int grade; //级长
  68.       String result = "";
  69.       String strTmp = "";
  70.       //得到当级长
  71.       grade = intPart.length() / GRADE;
  72.       //调整级次长度
  73.       if(intPart.length() % GRADE != 0) grade += 1;
  74.       //对每级数字处理
  75.       for(int i = grade; i >= 1; i--){
  76.           strTmp = getNowGradeVal(intPart, i);//取得当前级次数字
  77.           result += getSubUnit(strTmp);//转换大写
  78.           result = dropZero(result);//除零
  79.           //加级次单位
  80.           if( i>1 ) //末位不加单位
  81.               //单位不能相连续
  82.               if(getSubUnit(strTmp).equals("零零零零")){
  83.                   result += "零"+GRADEUNIT.substring(i - 1, i);
  84.               }else{
  85.                   result += GRADEUNIT.substring(i - 1, i);
  86.               }
  87.       }
  88.       return result;
  89.   }
  90.   private static String getNowGradeVal(String strVal,int grade){
  91.       //得到当前级次的串
  92.       String rst;
  93.       if(strVal.length() <= grade * GRADE)
  94.           rst = strVal.substring(0,strVal.length() - (grade-1)*GRADE);
  95.       else
  96.           rst = strVal.substring(strVal.length() - grade*GRADE,strVal.length() - (grade-1)*GRADE);
  97.       return rst;
  98.   }
  99.   private static String getSubUnit(String strVal){
  100.       //数值转换
  101.       String rst = "";
  102.       for(int i = 0;i< strVal.length(); i++){
  103.           String s = strVal.substring(i,i+1);
  104.           int num = Integer.parseInt(s);
  105.           if(num == 0){
  106.               //“零”作特殊处理
  107.               if(i != strVal.length()) //转换后数末位不能为零
  108.                   rst += "零";
  109.           }else{
  110.               //If IntKey = 1 And i = 2 Then
  111.                   //“壹拾”作特殊处理
  112.                   //“壹拾”合理
  113.               //Else
  114.                   rst += NUM.substring(num,num+1);
  115.               //End If
  116.               //追加单位
  117.               if(i != strVal.length()-1 )//个位不加单位
  118.                 rst += UNIT.substring(i+4-strVal.length(),i+4-strVal.length()+1);
  119.           }
  120.       }
  121.       return rst;
  122.   }
  123.   private static String dropZero(String strVal){
  124.       //去除连继的“零”
  125.       String strRst;
  126.       String strBefore; //前一位置字符
  127.       String strNow;    //现在位置字符
  128.       strBefore = strVal.substring(0,1);
  129.       strRst = strBefore;
  130.       for(int i= 1; i<strVal.length(); i++) {
  131.           strNow = strVal.substring(i, i+1);
  132.           if(strNow.equals("零") && strBefore.equals("零"))
  133.               ;//同时为零
  134.           else
  135.               strRst += strNow;
  136.           strBefore = strNow;
  137.       }
  138.       //末位去零
  139.       if(strRst.substring(strRst.length()-1, strRst.length()).equals("零"))
  140.         strRst = strRst.substring(0,strRst.length()-1);
  141.       return strRst;
  142.   }
  143.   public static void main(String[] args) {
  144.     System.out.println(RMB.toBigAmt(10052345.00D));
  145.     System.out.println(RMB.toBigAmt(0.00D));
  146.     System.out.println(RMB.toBigAmt(0.60D));
  147.     System.out.println(RMB.toBigAmt(00.60D));
  148.     System.out.println(RMB.toBigAmt(150.2101D));
  149.     System.out.println(RMB.toBigAmt(15400089666.234D));
  150.     System.out.println(RMB.toBigAmt(22200004444.2347D));
  151.   }


3.Java获取文件本身所在磁盘位置


们在做java开发(纯java程序,或者java web开发)时,经常会遇到需要读取配置文件的需求,如果我们将文件所在位置的信息直接写到程序中,例如:E:/workspace/JavaGUI/bin/com/util这个目录,这样虽然可行,但是,却产生了很大的局限性,因为读取的文件必须要要满足在E:/workspace/JavaGUI/bin/com/util之下才能够被正常读取,否则java抛异常。那如果在没有E盘盘符的服务器上,这样的程序是没办法执行的。所以就需要我们的程序能够读取当前文件的所在位置,从而确定文件的物理磁盘位置,而不是手动写入这个位置。

        以下程序,就实现了这个功能

  1.     /**
  2.      * 得到类的路径,例如E:/workspace/JavaGUI/bin/com/util
  3.      * @return
  4.      * @throws java.lang.Exception
  5.      */
  6.     public String getClassPath() throws Exception {
  7.         try {
  8.             String strClassName = getClass().getName();
  9.             String strPackageName = "";
  10.             if (getClass().getPackage() != null) {
  11.                 strPackageName = getClass().getPackage().getName();
  12.             }
  13.             String strClassFileName = "";
  14.             if (!"".equals(strPackageName)) {
  15.                 strClassFileName = strClassName.substring(strPackageName.length() + 1,
  16.                         strClassName.length());
  17.             } else {
  18.                 strClassFileName = strClassName;
  19.             }
  20.             URL url = null;
  21.             url = getClass().getResource(strClassFileName + ".class");
  22.             String strURL = url.toString();
  23.             strURL = strURL.substring(strURL.indexOf('/') + 1, strURL
  24.                     .lastIndexOf('/'));
  25.             //返回当前类的路径,并且处理路径中的空格,因为在路径中出现的空格如果不处理的话,
  26.             //在访问时就会从空格处断开,那么也就取不到完整的信息了,这个问题在web开发中尤其要注意
  27.             return strURL.replaceAll("%20"" ");
  28.         } catch (Exception ex) {
  29.             ex.printStackTrace();
  30.             throw ex;
  31.         }
  32.     }



4.Java中数据处理工具类

 在开发java项目时,经常都需要频繁处理数据,如果能非常合适、严谨的处理数据,那么将对程序有莫大的好处,例如,提高程序的稳定性,而且有时候数据在使用前是必须处理的,否则就会出错。例如,在操作前对被除数的处理(如果是0怎么办)、字符串转化、编码转换等,针对项目开发中对数据的频繁操作,在我们程序的开发过程中是很有必要对这些处理数据的工具方法进行统一归类使用的,而下面的这个工具类就封装了很多对基础数据的处理操作的方法。因为方法很多,为了方便查询,我先对方法及其实现的功能列了一个清单,如下:

        同时也希望大家能把自己使用的工具类发上来共享,谢谢。

 

一、功能方法目录清单:

1、getString(String sSource)的功能是判断参数是否为空,为空返回"",否则返回其值;

2、getString(int iSource)的功能是判断参数是否为0,为0则返回"",否则返回其值;

3、GBKtoISO(String s)的功能是进行编码转换,由GBK转为 iso-8859-1;

4、ISOtoGBK(String s)的功能是进行编码转换,由iso-8859-1 转为 GBK;

5、getArray(String[] aSource)的功能是判断参数是否为空,为空则返回一个长度为0的字符串数组,否则返回其值;

6、getInt(String sSource)的功能是判断参数是否为空,为空则返回0,不为空则返回其整型值;

7、getIntArray(String[] aSource)的功能是判断参数是否为空,为空则返回一个长度为0的整形数组,否则返回其值;

8、getDouble(String sSource)的功能是判断参数是否为空,为空则返回0,不为空则返回其整型值;

9、isContain(String sSource, String sItem)的功能是查找以逗号分隔的源字符串是否包含给定字符串;

10、isContain(String[] aSource, String sItem)的功能是查找源字符串数组中是否包含给定字符串;

11、delete(String source, String subString)的功能是将指定字符串从源字符串中删除掉,并返回替换后的结果字符串;

12、replace(String source, String oldString, String newString)的功能是用新字符串替换源字符串中的旧字符串;

13、increaseOne(String sSource)的功能是将给定的源字符串加1 例如:“0001” 经本函数转换后返回为“0002”;

14、intToStr(int val, int len)的功能是将给定的整数转化成字符串,结果字符串的长度为给定长度,不足位数的左端补"0";

15、arrayAddSign(String[] aSource, String sChar)的功能是将数组中的每个元素两端加上给定的符号;

16、arrayToString(String[] aSource)的功能是将数组中的元素连成一个以逗号分隔的字符串;

17、arrayToString(int[] aSource)的功能是将数组中的元素连成一个以逗号分隔的字符串;

18、arrayToString(String[] aSource, String sChar)的功能是将数组中的元素连成一个以给定字符分隔的字符串;

19、arrayAppend(String[] array1, String[] array2)的功能是将两个字符串的所有元素连结为一个字符串数组;

20、arrayAppend(Object[] array1, Object[] array2)的功能是将两个对象数组中的所有元素连结为一个对象数组;

21、strToArray(String sSource)的功能是拆分以逗号分隔的字符串,并存入String数组中;

22、strToArray(String sSource, String sChar)的功能是拆分以给定分隔符分隔的字符串,并存入字符串数组中;

23、strToArray(String sSource, char sChar)的功能是拆分以给定分隔符分隔的字符串,并存入整型数组中;

24、addMark(String sSource)的功能是将以逗号分隔的字符串的每个元素加上单引号 如: 1000,1001,1002 --> '1000','1001','1002';

25、deleteFile(String fileName)的功能是删除磁盘上的文件;

26、isNumber(String strInput)的功能是判断字符串是否可转换成数字;

27、isIp(String strIp)的功能是判断输入的字符是否是IP地址的形式;

  1. import java.io.File;
  2. import java.io.Serializable;
  3. import java.math.BigDecimal;
  4. import java.util.Hashtable;
  5. import java.util.Set;
  6. import java.util.StringTokenizer;
  7. import java.util.Vector;
  8. /*******************************************************************************
  9.  * 文件名称:Function.java<br>
  10.  * 功能描述:工具类,封装一些常用的操作<br>
  11.  ******************************************************************************/
  12. public class Function implements Serializable {
  13.     private static final long serialVersionUID = 1L;
  14.     public Function() {
  15.     }
  16.     public static void main(String args[]) {
  17.     }
  18.     /**
  19.      * 判断参数是否为空,为空则返回"",否则返回其值
  20.      * @param sSource 源字符串
  21.      * @return 字符串
  22.      */
  23.     public String getString(String sSource) {
  24.         String sReturn = "";
  25.         if (sSource != null) {
  26.             sReturn = sSource;
  27.         }
  28.         return sReturn;
  29.     }
  30.     /**
  31.      * 判断参数是否为0,为0则返回"",否则返回其值
  32.      * @param iSource 源字符串
  33.      * @return 字符串
  34.      */
  35.     public static String getString(int iSource) {
  36.         if (iSource == 0) {
  37.             return "";
  38.         } else {
  39.             return "" + iSource;
  40.         }
  41.     }
  42.     /**
  43.      * 转码:GBK ----> iso-8859-1
  44.      * @param s 转码字段
  45.      * @return 转码后的字段
  46.      */
  47.     public static String GBKtoISO(String s) {
  48.         try {
  49.             s = new String(s.getBytes("GBK"), "iso-8859-1");
  50.         } catch (Exception e) {
  51.         }
  52.         return s;
  53.     }
  54.     /**
  55.      * 转码:iso-8859-1 ----> GBK
  56.      * @param s 转码字段
  57.      * @return 转码后的字段
  58.      */
  59.     public static String ISOtoGBK(String s) {
  60.         try {
  61.             s = new String(s.getBytes("iso-8859-1"), "GBK");
  62.         } catch (Exception e) {
  63.         }
  64.         return s;
  65.     }
  66.     /**
  67.      * 判断参数是否为空,为空则返回一个长度为0的字符串数组,否则返回其值
  68.      * @param aSource 源字符串数组
  69.      * @return 字符串
  70.      */
  71.     public String[] getArray(String[] aSource) {
  72.         String aReturn[] = new String[0];
  73.         if (aSource != null) {
  74.             aReturn = aSource;
  75.         }
  76.         return aReturn;
  77.     }
  78.     /**
  79.      * 判断参数是否为空,为空则返回0,不为空则返回其整型值
  80.      * @param sSource  源字符串
  81.      * @return 整型数
  82.      */
  83.     public int getInt(String sSource) {
  84.         int iReturn = 0;
  85.         if (sSource != null && !sSource.equals("")) {
  86.             iReturn = Integer.parseInt(sSource);
  87.         }
  88.         return iReturn;
  89.     }
  90.     /**
  91.      * 判断参数是否为空,为空则返回一个长度为0的整形数组,否则返回其值
  92.      * @param aSource 源字符串数组
  93.      * @return 整形数组
  94.      */
  95.     public int[] getIntArray(String[] aSource) {
  96.         int iReturn[] = new int[0];
  97.         if (aSource != null) {
  98.             iReturn = new int[aSource.length];
  99.             for (int i = 0; i < aSource.length; i++) {
  100.                 iReturn[i] = Integer.parseInt(aSource[i]);
  101.             }
  102.         }
  103.         return iReturn;
  104.     }
  105.     /**
  106.      * 判断参数是否为空,为空则返回0,不为空则返回其整型值 
  107.      * @param sSource 源字符串
  108.      * @return Double数
  109.      */
  110.     public double getDouble(String sSource) {
  111.         double dReturn = 0.00;
  112.         if (sSource != null && !sSource.equals("")) {
  113.             dReturn = (new Double(sSource)).doubleValue();
  114.         }
  115.         return dReturn;
  116.     }
  117.     /**
  118.      * 查找以逗号分隔的源字符串是否包含给定字符串
  119.      * @param sSource :源字符串
  120.      * @param sItem :子串
  121.      * @return 是否包含
  122.      */
  123.     public boolean isContain(String sSource, String sItem) {
  124.         boolean isReturn = false;
  125.         StringTokenizer st = null;
  126.         st = new StringTokenizer(sSource, ",");
  127.         while (st.hasMoreTokens()) {
  128.             if (sItem.equals(st.nextToken())) {
  129.                 isReturn = true;
  130.                 break;
  131.             }
  132.         }
  133.         return isReturn;
  134.     }
  135.     /**
  136.      * 查找源字符串数组中是否包含给定字符串
  137.      * @param aSource :源字符串数组
  138.      * @param sItem :子串
  139.      * @return 是否包含
  140.      */
  141.     public boolean isContain(String[] aSource, String sItem) {
  142.         boolean isReturn = false;
  143.         for (int i = 0; i < aSource.length; i++) {
  144.             if (sItem.equals(aSource[i])) {
  145.                 isReturn = true;
  146.                 break;
  147.             }
  148.         }
  149.         return isReturn;
  150.     }
  151.     /**
  152.      * 将指定字符串从源字符串中删除掉,并返回替换后的结果字符串
  153.      * @param source 源字符串
  154.      * @param subString 要删除的字符
  155.      * @return 替换后的字符串
  156.      */
  157.     public String delete(String source, String subString) {
  158.         StringBuffer output = new StringBuffer();
  159.          //源字符串长度
  160.         int lengthOfSource = source.length();
  161.         //开始搜索位置
  162.         int posStart = 0
  163.         //搜索到老字符串的位置
  164.         int pos; 
  165.         while ((pos = source.indexOf(subString, posStart)) >= 0) {
  166.             output.append(source.substring(posStart, pos));
  167.             posStart = pos + 1;
  168.         }
  169.         if (posStart < lengthOfSource) {
  170.             output.append(source.substring(posStart));
  171.         }
  172.         return output.toString();
  173.     }
  174.     /**
  175.      * 此函数有三个输入参数,源字符串(将被操作的字符串),原字符串中被替换的字符串(旧字符串)
  176.      * 替换的字符串(新字符串),函数接收源字符串、旧字符串、新字符串三个值后,
  177.      * 用新字符串代替源字符串中的旧字符串并返回结果
  178.      * @param source 源字符串
  179.      * @param oldString 旧字符串
  180.      * @param newString 新字符串
  181.      * @return 替换后的字符串
  182.      */
  183.     public static String replace(String source, String oldString,
  184.             String newString) {
  185.         StringBuffer output = new StringBuffer();
  186.         int lengthOfSource = source.length(); // 源字符串长度
  187.         int lengthOfOld = oldString.length(); // 老字符串长度
  188.         int posStart = 0// 开始搜索位置
  189.         int pos; // 搜索到老字符串的位置
  190.         while ((pos = source.indexOf(oldString, posStart)) >= 0) {
  191.             output.append(source.substring(posStart, pos));
  192.             output.append(newString);
  193.             posStart = pos + lengthOfOld;
  194.         }
  195.         if (posStart < lengthOfSource) {
  196.             output.append(source.substring(posStart));
  197.         }
  198.         return output.toString();
  199.     }
  200.     /**
  201.      * 将给定的源字符串加1 例如:“0001” 经本函数转换后返回为“0002”
  202.      * @param sSource :源字符串
  203.      * @return 返回字符串
  204.      */
  205.     public String increaseOne(String sSource) {
  206.         String sReturn = null;
  207.         int iSize = 0;
  208.         iSize = sSource.length();
  209.         long l = (new Long(sSource)).longValue();
  210.         l++;
  211.         sReturn = String.valueOf(l);
  212.         for (int i = sReturn.length(); i < iSize; i++) {
  213.             sReturn = "0" + sReturn;
  214.         }
  215.         return sReturn;
  216.     }
  217.     /**
  218.      * 将给定的整数转化成字符串,结果字符串的长度为给定长度,不足位数的左端补"0"
  219.      * 例如val=10,len=5,那么生成的字符串为"00010"
  220.      * @param val 将被转化成字符串的整数
  221.      * @param len 转化后的长度
  222.      * @return String 返回值
  223.      */
  224.     public String intToStr(int val, int len) {
  225.         String sReturn = new String();
  226.         sReturn = String.valueOf(val);
  227.         if (sReturn.length() < len) {
  228.             for (int i = len - sReturn.length(); i > 0; i--) {
  229.                 sReturn = "0" + sReturn;
  230.             }
  231.         }
  232.         return sReturn;
  233.     }
  234.     /**
  235.      * 将数组中的每个元素两端加上给定的符号
  236.      * @param aSource 源数组
  237.      * @param sChar 符号
  238.      * @return 处理后的字符串数组
  239.      */
  240.     public String[] arrayAddSign(String[] aSource, String sChar) {
  241.         String aReturn[] = new String[aSource.length];
  242.         for (int i = 0; i < aSource.length; i++) {
  243.             aReturn[i] = sChar + aSource[i] + sChar;
  244.         }
  245.         return aReturn;
  246.     }
  247.     /**
  248.      * 将数组中的元素连成一个以逗号分隔的字符串
  249.      * @param aSource 源数组
  250.      * @return 字符串
  251.      */
  252.     public String arrayToString(String[] aSource) {
  253.         String sReturn = "";
  254.         for (int i = 0; i < aSource.length; i++) {
  255.             if (i > 0) {
  256.                 sReturn += ",";
  257.             }
  258.             sReturn += aSource[i];
  259.         }
  260.         return sReturn;
  261.     }
  262.     /**
  263.      * 将数组中的元素连成一个以逗号分隔的字符串
  264.      * @param aSource 源数组
  265.      * @return 字符串
  266.      */
  267.     public String arrayToString(int[] aSource) {
  268.         String sReturn = "";
  269.         for (int i = 0; i < aSource.length; i++) {
  270.             if (i > 0) {
  271.                 sReturn += ",";
  272.             }
  273.             sReturn += aSource[i];
  274.         }
  275.         return sReturn;
  276.     }
  277.     /**
  278.      * 将数组中的元素连成一个以给定字符分隔的字符串
  279.      * @param aSource 源数组
  280.      * @param sChar 分隔符
  281.      * @return 字符串
  282.      */
  283.     public String arrayToString(String[] aSource, String sChar) {
  284.         String sReturn = "";
  285.         for (int i = 0; i < aSource.length; i++) {
  286.             if (i > 0) {
  287.                 sReturn += sChar;
  288.             }
  289.             sReturn += aSource[i];
  290.         }
  291.         return sReturn;
  292.     }
  293.     /**
  294.      * 将两个字符串的所有元素连结为一个字符串数组
  295.      * @param array1 源字符串数组1
  296.      * @param array2 源字符串数组2
  297.      * @return String[]
  298.      */
  299.     public String[] arrayAppend(String[] array1, String[] array2) {
  300.         int iLen = 0;
  301.         String aReturn[] = null;
  302.         if (array1 == null) {
  303.             array1 = new String[0];
  304.         }
  305.         if (array2 == null) {
  306.             array2 = new String[0];
  307.         }
  308.         iLen = array1.length;
  309.         aReturn = new String[iLen + array2.length];
  310.         /**
  311.          * 将第一个字符串数组的元素加到结果数组中
  312.          */
  313.         for (int i = 0; i < iLen; i++) {
  314.             aReturn[i] = array1[i];
  315.         }
  316.         /**
  317.          * 将第二个字符串数组的元素加到结果数组中
  318.          */
  319.         for (int i = 0; i < array2.length; i++) {
  320.             aReturn[iLen + i] = array2[i];
  321.         }
  322.         return aReturn;
  323.     }
  324.     /**
  325.      * 将两个对象数组中的所有元素连结为一个对象数组
  326.      * @param array1 源字符串数组1
  327.      * @param array2 源字符串数组2
  328.      * @return Object[]
  329.      */
  330.     public Object[] arrayAppend(Object[] array1, Object[] array2) {
  331.         int iLen = 0;
  332.         Object aReturn[] = null;
  333.         if (array1 == null) {
  334.             array1 = new Object[0];
  335.         }
  336.         if (array2 == null) {
  337.             array2 = new Object[0];
  338.         }
  339.         iLen = array1.length;
  340.         aReturn = new Object[iLen + array2.length];
  341.         /**
  342.          * 将第一个对象数组的元素加到结果数组中
  343.          */
  344.         for (int i = 0; i < iLen; i++) {
  345.             aReturn[i] = array1[i];
  346.         }
  347.         /**
  348.          * 将第二个对象数组的元素加到结果数组中
  349.          */
  350.         for (int i = 0; i < array2.length; i++) {
  351.             aReturn[iLen + i] = array2[i];
  352.         }
  353.         return aReturn;
  354.     }
  355.     /**
  356.      * 拆分以逗号分隔的字符串,并存入String数组中
  357.      * @param sSource 源字符串
  358.      * @return String[]
  359.      */
  360.     public String[] strToArray(String sSource) {
  361.         String aReturn[] = null;
  362.         StringTokenizer st = null;
  363.         st = new StringTokenizer(sSource, ",");
  364.         aReturn = new String[st.countTokens()];
  365.         int i = 0;
  366.         while (st.hasMoreTokens()) {
  367.             aReturn[i] = st.nextToken();
  368.             i++;
  369.         }
  370.         return aReturn;
  371.     }
  372.     /**
  373.      * 拆分以给定分隔符分隔的字符串,并存入字符串数组中
  374.      * @param sSource  源字符串
  375.      * @param sChar 分隔符
  376.      * @return String[]
  377.      */
  378.     public static String[] strToArray(String sSource, String sChar) {
  379.         String aReturn[] = null;
  380.         StringTokenizer st = null;
  381.         st = new StringTokenizer(sSource, sChar);
  382.         int i = 0;
  383.         aReturn = new String[st.countTokens()];
  384.         while (st.hasMoreTokens()) {
  385.             aReturn[i] = st.nextToken();
  386.             i++;
  387.         }
  388.         return aReturn;
  389.     }
  390.     /**
  391.      * 拆分以给定分隔符分隔的字符串,并存入整型数组中
  392.      * @param sSource 源字符串
  393.      * @param sChar 分隔符
  394.      * @return int[]
  395.      */
  396.     public static int[] strToArray(String sSource, char sChar) {
  397.         int aReturn[] = null;
  398.         StringTokenizer st = null;
  399.         st = new StringTokenizer(sSource, String.valueOf(sChar));
  400.         int i = 0;
  401.         aReturn = new int[st.countTokens()];
  402.         while (st.hasMoreTokens()) {
  403.             aReturn[i] = Integer.parseInt(st.nextToken());
  404.             i++;
  405.         }
  406.         return aReturn;
  407.     }
  408.     /**
  409.      * 将以逗号分隔的字符串的每个元素加上单引号 如: 1000,1001,1002 --> '1000','1001','1002'
  410.      * @param sSource 源串
  411.      * @return String
  412.      */
  413.     public String addMark(String sSource) {
  414.         String sReturn = "";
  415.         StringTokenizer st = null;
  416.         st = new StringTokenizer(sSource, ",");
  417.         if (st.hasMoreTokens()) {
  418.             sReturn += "'" + st.nextToken() + "'";
  419.         }
  420.         while (st.hasMoreTokens()) {
  421.             sReturn += "," + "'" + st.nextToken() + "'";
  422.         }
  423.         return sReturn;
  424.     }
  425.     /**
  426.      * 删除磁盘上的文件
  427.      * @param fileName 文件全路径
  428.      * @return boolean
  429.      */
  430.     public boolean deleteFile(String fileName) {
  431.         File file = new File(fileName);
  432.         return file.delete();
  433.     }
  434.     /**
  435.      * 判断字符串是否可转换成数字
  436.      * @param fileName 源串
  437.      * @return boolean
  438.      */
  439.     public static boolean isNumber(String strInput){
  440.         boolean bRs=false;
  441.         int nRs=0;
  442.         try{
  443.             nRs=Integer.parseInt(strInput);
  444.             bRs=true;
  445.         }catch(Exception e){
  446.             bRs=false;
  447.         }
  448.             return bRs;
  449.     }
  450.     /**
  451.      * 判断输入的字符是否是IP地址的形式
  452.      * @param fileName 源串
  453.      * @return boolean
  454.      */
  455.     public static boolean isIp(String strIp){
  456.         boolean bRs=false;
  457.         int nCount=0;
  458.         try{
  459.             String strTmp="";
  460.             StringTokenizer st=new StringTokenizer(strIp,".");
  461.             while (st.hasMoreElements()){
  462.                 nCount++;
  463.                 strTmp=st.nextToken();
  464.                 if(isBigger("1",strTmp) || isBigger(strTmp,"255"))
  465.                     return false;
  466.             }
  467.             if (nCount==4)
  468.                 bRs=true;
  469.         } catch(Exception e){
  470.             bRs=false;
  471.         }
  472.         return bRs;
  473.     }
  474. }

        此类包含的方法已经在实际项目开发中使用通过,这样把平常开发中经常用到的小功能封装到一个公共类里面,即减少了代码量、提高了代码重用率,又可以很方便的查询、使用,统一修改,提高了劳动率,甚至有些结构功能相似的系统间接口小程序都可以直接保留其他接口的功能框架,只改变其中的业务逻辑就可以了,非常方便


5.Java日期处理工具类

public class DateUtil
{
	//默认显示日期的格式
	public static final String DATAFORMAT_STR = "yyyy-MM-dd";
	
	//默认显示日期的格式
	public static final String YYYY_MM_DATAFORMAT_STR = "yyyy-MM";
	
	//默认显示日期时间的格式
	public static final String DATATIMEF_STR = "yyyy-MM-dd HH:mm:ss";
	
	//默认显示简体中文日期的格式
	public static final String ZHCN_DATAFORMAT_STR = "yyyy年MM月dd日";
	
	//默认显示简体中文日期时间的格式
	public static final String ZHCN_DATATIMEF_STR = "yyyy年MM月dd日HH时mm分ss秒";
	
	//默认显示简体中文日期时间的格式
	public static final String ZHCN_DATATIMEF_STR_4yMMddHHmm = "yyyy年MM月dd日HH时mm分";
	
	private static DateFormat dateFormat = null;
	
	private static DateFormat dateTimeFormat = null;
	
	private static DateFormat zhcnDateFormat = null;
	
	private static DateFormat zhcnDateTimeFormat = null;
	static
	{
		dateFormat = new SimpleDateFormat(DATAFORMAT_STR);
		dateTimeFormat = new SimpleDateFormat(DATATIMEF_STR);
		zhcnDateFormat = new SimpleDateFormat(ZHCN_DATAFORMAT_STR);
		zhcnDateTimeFormat = new SimpleDateFormat(ZHCN_DATATIMEF_STR);
	}
	
	private static DateFormat getDateFormat(String formatStr)
	{
		if (formatStr.equalsIgnoreCase(DATAFORMAT_STR))
		{
			return dateFormat;
		}
		else
			if (formatStr.equalsIgnoreCase(DATATIMEF_STR))
			{
				return dateTimeFormat;
			}
			else
				if (formatStr.equalsIgnoreCase(ZHCN_DATAFORMAT_STR))
				{
					return zhcnDateFormat;
				}
				else
					if (formatStr.equalsIgnoreCase(ZHCN_DATATIMEF_STR))
					{
						return zhcnDateTimeFormat;
					}
					else
					{
						return new SimpleDateFormat(formatStr);
					}
	}
	
	/**
	 * 按照默认显示日期时间的格式"yyyy-MM-dd HH:mm:ss",转化dateTimeStr为Date类型
	 * dateTimeStr必须是"yyyy-MM-dd HH:mm:ss"的形式
	 * @param dateTimeStr
	 * @return
	 */
	public static Date getDate(String dateTimeStr)
	{
		return getDate(dateTimeStr, DATATIMEF_STR);
	}
	
	/**
	 * 按照默认formatStr的格式,转化dateTimeStr为Date类型
	 * dateTimeStr必须是formatStr的形式
	 * @param dateTimeStr
	 * @param formatStr
	 * @return
	 */
	public static Date getDate(String dateTimeStr, String formatStr)
	{
		try
		{
			if (dateTimeStr == null || dateTimeStr.equals(""))
			{
				return null;
			}
			DateFormat sdf = getDateFormat(formatStr);
			java.util.Date d = sdf.parse(dateTimeStr);
			return d;
		}
		catch (ParseException e)
		{
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 将YYYYMMDD转换成Date日期
	 * @param date
	 * @return
	 * @throws BusinessException
	 */
	public static Date transferDate(String date) throws Exception
	{
		if (date == null || date.length() < 1)
			return null;
		
		if (date.length() != 8)
			throw new Exception("日期格式错误");
		String con = "-";
		
		String yyyy = date.substring(0, 4);
		String mm = date.substring(4, 6);
		String dd = date.substring(6, 8);
		
		int month = Integer.parseInt(mm);
		int day = Integer.parseInt(dd);
		if (month < 1 || month > 12 || day < 1 || day > 31)
			throw new Exception("日期格式错误");
		
		String str = yyyy + con + mm + con + dd;
		return DateUtil.getDate(str, DateUtil.DATAFORMAT_STR);
	}
	
	/**
	 * 将YYYY-MM-DD日期转换成yyyymmdd格式字符串
	 * @param date
	 * @return
	 */
	public static String getYYYYMMDDDate(Date date)
	{
		if (date == null)
			return null;
		String yyyy = getYear(date) + "";
		String mm = getMonth(date) + "";
		String dd = getDay(date) + "";
		
		mm = StringUtil.rightAlign(mm, 2, "0");
		dd = StringUtil.rightAlign(dd, 2, "0");
		return yyyy + mm + dd;
	}
	
	/**
	 * 将YYYY-MM-DD日期转换成YYYYMMDDHHMMSS格式字符串
	 * @param date
	 * @return
	 */
	public static String getYYYYMMDDHHMMSSDate(Date date)
	{
		if (date == null)
			return null;
		String yyyy = getYear(date) + "";
		String mm = getMonth(date) + "";
		String dd = getDay(date) + "";
		String hh = getHour(date) + "";
		String min = getMin(date) + "";
		String ss = getSecond(date) + "";
		
		mm = StringUtil.rightAlign(mm, 2, "0");
		dd = StringUtil.rightAlign(dd, 2, "0");
		hh = StringUtil.rightAlign(hh, 2, "0");
		min = StringUtil.rightAlign(min, 2, "0");
		ss = StringUtil.rightAlign(ss, 2, "0");
		
		return yyyy + mm + dd + hh + min + ss;
	}
	
	/**
	 * 将YYYY-MM-DD日期转换成yyyymmdd格式字符串
	 * @param date
	 * @return
	 */
	public static String getYYYYMMDDDate(String date)
	{
		return getYYYYMMDDDate(getDate(date, DATAFORMAT_STR));
	}
	
	/**
	 * 将Date转换成字符串“yyyy-mm-dd hh:mm:ss”的字符串
	 * @param date
	 * @return
	 */
	public static String dateToDateString(Date date)
	{
		return dateToDateString(date, DATATIMEF_STR);
	}
	
	/**
	 * 将Date转换成formatStr格式的字符串
	 * @param date
	 * @param formatStr
	 * @return
	 */
	public static String dateToDateString(Date date, String formatStr)
	{
		DateFormat df = getDateFormat(formatStr);
		return df.format(date);
	}
	
	/**
	 * 返回一个yyyy-MM-dd HH:mm:ss 形式的日期时间字符串中的HH:mm:ss
	 * @param dateTime
	 * @return
	 */
	public static String getTimeString(String dateTime)
	{
		return getTimeString(dateTime, DATATIMEF_STR);
	}
	
	/**
	 * 返回一个formatStr格式的日期时间字符串中的HH:mm:ss
	 * @param dateTime
	 * @param formatStr
	 * @return
	 */
	public static String getTimeString(String dateTime, String formatStr)
	{
		Date d = getDate(dateTime, formatStr);
		String s = dateToDateString(d);
		return s.substring(DATATIMEF_STR.indexOf('H'));
	}
	
	/**
	 * 获取当前日期yyyy-MM-dd的形式
	 * @return
	 */
	public static String getCurDate()
	{
		//return dateToDateString(new Date(),DATAFORMAT_STR);
		return dateToDateString(Calendar.getInstance().getTime(), DATAFORMAT_STR);
	}
	
	/**
	 * 获取当前日期yyyy年MM月dd日的形式
	 * @return
	 */
	public static String getCurZhCNDate()
	{
		return dateToDateString(new Date(), ZHCN_DATAFORMAT_STR);
	}
	
	/**
	 * 获取当前日期时间yyyy-MM-dd HH:mm:ss的形式
	 * @return
	 */
	public static String getCurDateTime()
	{
		return dateToDateString(new Date(), DATATIMEF_STR);
	}
	
	/**
	 * 获取当前日期时间yyyy年MM月dd日HH时mm分ss秒的形式
	 * @return
	 */
	public static String getCurZhCNDateTime()
	{
		return dateToDateString(new Date(), ZHCN_DATATIMEF_STR);
	}
	
	/**
	 * 获取日期d的days天后的一个Date
	 * @param d
	 * @param days
	 * @return
	 */
	public static Date getInternalDateByDay(Date d, int days)
	{
		Calendar now = Calendar.getInstance(TimeZone.getDefault());
		now.setTime(d);
		now.add(Calendar.DATE, days);
		return now.getTime();
	}
	
	public static Date getInternalDateByMon(Date d, int months)
	{
		Calendar now = Calendar.getInstance(TimeZone.getDefault());
		now.setTime(d);
		now.add(Calendar.MONTH, months);
		return now.getTime();
	}
	
	public static Date getInternalDateByYear(Date d, int years)
	{
		Calendar now = Calendar.getInstance(TimeZone.getDefault());
		now.setTime(d);
		now.add(Calendar.YEAR, years);
		return now.getTime();
	}
	
	public static Date getInternalDateBySec(Date d, int sec)
	{
		Calendar now = Calendar.getInstance(TimeZone.getDefault());
		now.setTime(d);
		now.add(Calendar.SECOND, sec);
		return now.getTime();
	}
	
	public static Date getInternalDateByMin(Date d, int min)
	{
		Calendar now = Calendar.getInstance(TimeZone.getDefault());
		now.setTime(d);
		now.add(Calendar.MINUTE, min);
		return now.getTime();
	}
	
	public static Date getInternalDateByHour(Date d, int hours)
	{
		Calendar now = Calendar.getInstance(TimeZone.getDefault());
		now.setTime(d);
		now.add(Calendar.HOUR_OF_DAY, hours);
		return now.getTime();
	}
	
	/**
	 * 根据一个日期字符串,返回日期格式,目前支持4种
	 * 如果都不是,则返回null
	 * @param DateString
	 * @return
	 */
	public static String getFormateStr(String DateString)
	{
		String patternStr1 = "[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}"; //"yyyy-MM-dd"
		String patternStr2 = "[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}\\s[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}"; //"yyyy-MM-dd HH:mm:ss";
		String patternStr3 = "[0-9]{4}年[0-9]{1,2}月[0-9]{1,2}日";//"yyyy年MM月dd日"
		String patternStr4 = "[0-9]{4}年[0-9]{1,2}月[0-9]{1,2}日[0-9]{1,2}时[0-9]{1,2}分[0-9]{1,2}秒";//"yyyy年MM月dd日HH时mm分ss秒"
		
		Pattern p = Pattern.compile(patternStr1);
		Matcher m = p.matcher(DateString);
		boolean b = m.matches();
		if (b)
			return DATAFORMAT_STR;
		p = Pattern.compile(patternStr2);
		m = p.matcher(DateString);
		b = m.matches();
		if (b)
			return DATATIMEF_STR;
		
		p = Pattern.compile(patternStr3);
		m = p.matcher(DateString);
		b = m.matches();
		if (b)
			return ZHCN_DATAFORMAT_STR;
		
		p = Pattern.compile(patternStr4);
		m = p.matcher(DateString);
		b = m.matches();
		if (b)
			return ZHCN_DATATIMEF_STR;
		return null;
	}
	
	/**
	 * 将一个"yyyy-MM-dd HH:mm:ss"字符串,转换成"yyyy年MM月dd日HH时mm分ss秒"的字符串
	 * @param dateStr
	 * @return
	 */
	public static String getZhCNDateTime(String dateStr)
	{
		Date d = getDate(dateStr);
		return dateToDateString(d, ZHCN_DATATIMEF_STR);
	}
	
	/**
	 * 将一个"yyyy-MM-dd"字符串,转换成"yyyy年MM月dd日"的字符串
	 * @param dateStr
	 * @return
	 */
	public static String getZhCNDate(String dateStr)
	{
		Date d = getDate(dateStr, DATAFORMAT_STR);
		return dateToDateString(d, ZHCN_DATAFORMAT_STR);
	}
	
	/**
	 * 将dateStr从fmtFrom转换到fmtTo的格式
	 * @param dateStr
	 * @param fmtFrom
	 * @param fmtTo
	 * @return
	 */
	public static String getDateStr(String dateStr, String fmtFrom, String fmtTo)
	{
		Date d = getDate(dateStr, fmtFrom);
		return dateToDateString(d, fmtTo);
	}
	
	/**
	 * 比较两个"yyyy-MM-dd HH:mm:ss"格式的日期,之间相差多少毫秒,time2-time1
	 * @param time1
	 * @param time2
	 * @return
	 */
	public static long compareDateStr(String time1, String time2)
	{
		Date d1 = getDate(time1);
		Date d2 = getDate(time2);
		return d2.getTime() - d1.getTime();
	}
	
	/**
	 * 将小时数换算成返回以毫秒为单位的时间
	 * @param hours
	 * @return
	 */
	public static long getMicroSec(BigDecimal hours)
	{
		BigDecimal bd;
		bd = hours.multiply(new BigDecimal(3600 * 1000));
		return bd.longValue();
	}
	
	/**
	 * 获取Date中的分钟
	 * @param d
	 * @return
	 */
	public static int getMin(Date d)
	{
		Calendar now = Calendar.getInstance(TimeZone.getDefault());
		now.setTime(d);
		return now.get(Calendar.MINUTE);
	}
	
	/**
	 * 获取Date中的小时(24小时)
	 * @param d
	 * @return
	 */
	public static int getHour(Date d)
	{
		Calendar now = Calendar.getInstance(TimeZone.getDefault());
		now.setTime(d);
		return now.get(Calendar.HOUR_OF_DAY);
	}
	
	/**
	 * 获取Date中的秒
	 * @param d
	 * @return
	 */
	public static int getSecond(Date d)
	{
		Calendar now = Calendar.getInstance(TimeZone.getDefault());
		now.setTime(d);
		return now.get(Calendar.SECOND);
	}
	
	/**
	 * 获取xxxx-xx-xx的日
	 * @param d
	 * @return
	 */
	public static int getDay(Date d)
	{
		Calendar now = Calendar.getInstance(TimeZone.getDefault());
		now.setTime(d);
		return now.get(Calendar.DAY_OF_MONTH);
	}
	
	/**
	 * 获取月份,1-12月
	 * @param d
	 * @return
	 */
	public static int getMonth(Date d)
	{
		Calendar now = Calendar.getInstance(TimeZone.getDefault());
		now.setTime(d);
		return now.get(Calendar.MONTH) + 1;
	}
	
	/**
	 * 获取19xx,20xx形式的年
	 * @param d
	 * @return
	 */
	public static int getYear(Date d)
	{
		Calendar now = Calendar.getInstance(TimeZone.getDefault());
		now.setTime(d);
		return now.get(Calendar.YEAR);
	}
	
	/**
	 * 得到d的上个月的年份+月份,如200505
	 * @return
	 */
	public static String getYearMonthOfLastMon(Date d)
	{
		Date newdate = getInternalDateByMon(d, -1);
		String year = String.valueOf(getYear(newdate));
		String month = String.valueOf(getMonth(newdate));
		return year + month;
	}
	
	/**
	 * 得到当前日期的年和月如200509
	 * @return String
	 */
	public static String getCurYearMonth()
	{
		Calendar now = Calendar.getInstance(TimeZone.getDefault());
		String DATE_FORMAT = "yyyyMM";
		java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(DATE_FORMAT);
		sdf.setTimeZone(TimeZone.getDefault());
		return (sdf.format(now.getTime()));
	}
	
	public static Date getNextMonth(String year, String month)
	{
		String datestr = year + "-" + month + "-01";
		Date date = getDate(datestr, DATAFORMAT_STR);
		return getInternalDateByMon(date, 1);
	}
	
	public static Date getLastMonth(String year, String month)
	{
		String datestr = year + "-" + month + "-01";
		Date date = getDate(datestr, DATAFORMAT_STR);
		return getInternalDateByMon(date, -1);
	}
	
	/**
	 * 得到日期d,按照页面日期控件格式,如"2001-3-16"
	 * @param d
	 * @return
	 */
	public static String getSingleNumDate(Date d)
	{
		return dateToDateString(d, DATAFORMAT_STR);
	}
	
	/**
	 * 得到d半年前的日期,"yyyy-MM-dd"
	 * @param d
	 * @return
	 */
	public static String getHalfYearBeforeStr(Date d)
	{
		return dateToDateString(getInternalDateByMon(d, -6), DATAFORMAT_STR);
	}
	
	/**
	 * 得到当前日期D的月底的前/后若干天的时间,<0表示之前,>0表示之后
	 * @param d
	 * @param days
	 * @return
	 */
	public static String getInternalDateByLastDay(Date d, int days)
	{
		
		return dateToDateString(getInternalDateByDay(d, days), DATAFORMAT_STR);
	}
	
	/**
	 * 日期中的年月日相加
	 *  @param field int  需要加的字段  年 月 日
	 * @param amount int 加多少
	 * @return String
	 */
	public static String addDate(int field, int amount)
	{
		int temp = 0;
		if (field == 1)
		{
			temp = Calendar.YEAR;
		}
		if (field == 2)
		{
			temp = Calendar.MONTH;
		}
		if (field == 3)
		{
			temp = Calendar.DATE;
		}
		
		String Time = "";
		try
		{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Calendar cal = Calendar.getInstance(TimeZone.getDefault());
			cal.add(temp, amount);
			Time = sdf.format(cal.getTime());
			return Time;
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
		
	}
	
	/**
	 * 获得系统当前月份的天数
	 * @return
	 */
	public static int getCurentMonthDay()
	{
		Date date = Calendar.getInstance().getTime();
		return getMonthDay(date);
	}
	
	/**
	 * 获得指定日期月份的天数
	 * @return
	 */
	public static int getMonthDay(Date date)
	{
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		return c.getActualMaximum(Calendar.DAY_OF_MONTH);
		
	}
	
	/**
	 * 获得指定日期月份的天数  yyyy-mm-dd
	 * @return
	 */
	public static int getMonthDay(String date)
	{
		Date strDate = getDate(date, DATAFORMAT_STR);
		return getMonthDay(strDate);
		
	}
	
	public static String getStringDate(Calendar cal)
	{
		
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		return format.format(cal.getTime());
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		//		//System.out.print(DateUtil.getDate("04:04:04","HH:mm:ss"));
		//		System.out.print("\n"+DateUtil.getCurZhCNDateTime());
		//		System.out.print("\n"+getFormateStr(DateUtil.getCurDate()));
		//		System.out.print("\n"+compareDateStr("1900-1-1 1:1:2","1900-1-1 1:1:3"));
		//		System.out.print("\n"+getDay(new Date()));
		//		System.out.print("\n"+getMonth(new Date()));
		//		System.out.print("\n"+getYear(new Date()));
		//		System.out.print("\n"+getMin(new Date()));
				System.out.print("\n"+new Date().getSeconds());
		/*Date d1 = new Date(2007,11,30);
		Date d2 = new Date(2007,12,1);
		if(d2.compareTo(d1)>0){
		    System.out.println("d2大于d1");
		}else{
		    System.out.println("d2小于d1");
		}*/

		System.out.println(addDate(1, 1));
		System.out.println(addDate(2, 1));
		System.out.println(addDate(3, 1));
		
		System.out.println(getYYYYMMDDHHMMSSDate(new Date()));
		
		System.out.println(getCurentMonthDay());
		
	}
	
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值