JAVA字符串转时间及编码格式转换等

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.text.*;
import java.util.*;


/**
 * <p>Title: 常用方法类</p>
 * <p>Description:提供  字符串替换 字符串分割 将ISO-8859-1编码转换为GB2312
 * 处理空字符串 处理空对象 将字符串转化为整数 断是否为整数 字符串转换为java.util.Date
 * 将java.util.Date 格式转换为字符串格式'yyyy-MM-dd HH:mm:ss'(24小时制)
 * 将java.util.Date 格式转换为字符串格式'yyyy-MM-dd HH:mm:ss a'(12小时制)
 * 取系统当前时间:返回只值为如下形式2002-10-30 20:24:39
 * 取系统当前时间:返回只值为如下形式2002-10-30 08:28:56 下午
 * 取系统当前时间:返回只值为如下形式2002-10-30</p>
 * <p>Copyright: Copyright (c) 2001</p>
 * <p>Company: </p>
 * @author unascribed
 * @version 1.0
 */
/**
 * 增加了判断对象所属类型的方法。例如:要测试某一对象obj是否是Map类型,
 * 	   调用此类中的CheckMap(obj)方法,若为Map对象,则返回True,否则返回False。
 */

public class cCharControl {
    /**
     *字符串替换
     *@param strFrom 要替换的目标子串
     *@param strTo 替换后的子串
     *@param strSource 原字符串
     *@return 替换后的字符串
     */
    public static String replace(String strSource, String strFrom, String strTo) {
        String strDest = "";

        int intFromLen = strFrom.length();
        int intPos;
        while ((intPos = strSource.indexOf(strFrom)) != -1) {
            strDest = strDest + strSource.substring(0, intPos);
            strDest = strDest + strTo;
            strSource = strSource.substring(intPos + intFromLen);
        }
        strDest = strDest + strSource;

        return strDest;
    }

    /**
     *计算一个字符串中的子串数量,
     */
    public static int childStrNo(String str, String delim) {
        int cur = 0;
        int numno = 1;
        do {

            cur = str.indexOf(delim);
            if (cur == -1) {
                break;
            }
            str = str.substring(cur + 1, str.length());
            numno = numno + 1;
        } while (true);

        return numno;

    }


    /**
     *字符串分割
     * @param str 原字符串
     * @param delim 分割子串
     * @return String[]
     */
    public static String[] split(String str, String delim) {
        int last = 0;
        int cur = 0;
        String[] result = null;
        ArrayList holder = new ArrayList();

        do {
            String tmp;
            cur = str.indexOf(delim, cur);
            if (cur == -1) {
                tmp = str.substring(last);
                holder.add(tmp);
                break;
            }
            tmp = str.substring(last, cur);
            holder.add(tmp);
            cur += delim.length();
            last = cur;
        } while (true);
        result = new String[holder.size()];
        for (int i = 0; i < holder.size(); i++) {
            result[i] = (String) holder.get(i);
        }

        return result;
    }

    /**
     * 将ISO-8859-1编码转换为 GB2312
     * @param str 目标字符串
     * @return String
     */
    public static String ISOtoGb2312(String str) {
        if (str == null) {
            return " ";
        }
        try {
            byte[] bytesStr = str.getBytes("ISO-8859-1");
            return new String(bytesStr, "GBK");
        } catch (Exception ex) {
            return str;
        }
    }

    public static String Gb2312toISO(String str) {
        if (str == null) {
            return " ";
        }
        try {
            byte[] bytesStr = str.getBytes("GBK");
            return new String(bytesStr, "ISO-8859-1");
        } catch (Exception ex) {
            return str;
        }
    }

    /**
     * 处理空字符串
     * @param str要处理的字符串 如果str为null返回""
     * @return String 如果str为null返回"" 否则返回str
     */
    public static String dealNull(String str) {
        String returnstr = null;
        if (str == null) {
            returnstr = "";
        } else {
            returnstr = str;
        }
        return returnstr;
    }

    /**
     *处理空对象
     *将null转化为""对象
     * @param obj:Object
     * @return Object
     */
    public static Object dealNull(Object obj) {
        Object returnstr = null;
        if (obj == null) {
            returnstr = (Object) ("");
        } else {
            returnstr = obj;
        }
        return returnstr;
    }

    /**
     *将字符串转化为整数
     *如果参数为null或“”或不能转换为整数则返回0
     *如“阿不错23”返回结果为0
     */
    public static int intToString(String s) {
        s = dealNull(s);
        int x = 0;
        if (s.equals("")) {
            return 0;
        }
        try {
            x = Integer.parseInt(s);
        } catch (Exception e) {}
        return x;
    }

    /**
     *断是否为数字整数
     * @param number
     * @return boolean:true or false
     */
    public static boolean isInt(String number) {
        try {
            Integer.parseInt(number);
            return true;
        } catch (NumberFormatException sqo) {
            return false;
        }
    }

    /**
     * 字符串转换为java.util.Date<br>
     * 支持格式为 yyyy.MM.dd G 'at' hh:mm:ss z 如 '2002-1-1 AD at 22:10:59 PSD'<br>
     * yy/MM/dd HH:mm:ss 如 '2002/1/1 17:55:00'<br>
     * yy/MM/dd HH:mm:ss pm  如 '2002/1/1 17:55:00 pm'<br>
     * yy-MM-dd HH:mm:ss 如 '2002-1-1 17:55:00' <br>
     * yy-MM-dd HH:mm:ss am 如 '2002-1-1 17:55:00 am' <br>
     * @param time String 字符串<br>
     * @return Date 日期<br>
     */
    public static Date stringToDate(String time) {
        SimpleDateFormat formatter;
        int tempPos = time.indexOf("AD");
        time = time.trim();
        formatter = new SimpleDateFormat("yyyy.MM.dd G 'at' hh:mm:ss z");
        if (tempPos > -1) {
            time = time.substring(0, tempPos) +
                   "公元" + time.substring(tempPos + "AD".length()); //china
            formatter = new SimpleDateFormat("yyyy.MM.dd G 'at' hh:mm:ss z");
        }
        tempPos = time.indexOf("-");
        if (tempPos > -1 && (time.indexOf(" ") < 0)) {
            formatter = new SimpleDateFormat("yyyyMMddHHmmssZ");
        } else if ((time.indexOf("/") > -1) && (time.indexOf(" ") > -1)) {
            formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        } else if ((time.indexOf("-") > -1) && (time.indexOf(" ") > -1)) {
            formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        } else if ((time.indexOf("/") > -1) && (time.indexOf("am") > -1) ||
                   (time.indexOf("pm") > -1)) {
            formatter = new SimpleDateFormat("yyyy-MM-dd KK:mm:ss a");
        } else if ((time.indexOf("-") > -1) && (time.indexOf("am") > -1) ||
                   (time.indexOf("pm") > -1)) {
            formatter = new SimpleDateFormat("yyyy-MM-dd KK:mm:ss a");
        }
        ParsePosition pos = new ParsePosition(0);
        java.util.Date ctime = formatter.parse(time, pos);

        return ctime;
    }

    /**
     * 将java.util.Date 格式转换为字符串格式'yyyy-MM-dd HH:mm:ss'(24小时制)<br>
     * 如Sat May 11 17:24:21 CST 2002 to '2002-05-11 17:24:21'<br>
     * @param time Date 日期<br>
     * @return String   字符串<br>
     */

    public static String dateToString(Date time) {
        SimpleDateFormat formatter;
        formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String ctime = formatter.format(time);

        return ctime;
    }

    /**
     * 将java.util.Date 格式转换为字符串格式'yyyyMMddHHmmss'(24小时制)<br>
     * 如Sat May 11 17:24:21 CST 2002 to '2002-05-11 17:24:21'<br>
     * @param time Date 日期<br>
     * @return String   字符串<br>
     * add by cye 2003-8-20
     */

    public static String dateToString11(Date time) {
        SimpleDateFormat formatter;
        formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String ctime = formatter.format(time);

        return ctime;
    }

    /**
     * 将java.util.Date 格式转换为字符串格式'yyyy-MM-dd HH:mm:ss a'(12小时制)<br>
     * 如Sat May 11 17:23:22 CST 2002 to '2002-05-11 05:23:22 下午'<br>
     * @param time Date 日期<br>
     * @param x int 任意整数如:1<br>
     * @return String 字符串<br>
     */
    public static String dateToString(Date time, int x) {
        SimpleDateFormat formatter;
        formatter = new SimpleDateFormat("yyyy-MM-dd KK:mm:ss a");
        String ctime = formatter.format(time);

        return ctime;
    }
    public static String dateToStringCustom(Date time,String format) {
       SimpleDateFormat formatter;
       formatter = new SimpleDateFormat(format);
       String ctime = formatter.format(time);

       return ctime;
   }

    /**
     *取系统当前时间:返回值为如下形式
     *020809123512
     * @return String
     */
    public static String Nowyymmddhhmmss() {
        String dd = dateToString(new Date());
        dd = dd.substring(2, 4) + dd.substring(5, 7) + dd.substring(8, 10) +
             dd.substring(11, 13) + dd.substring(14, 16) + dd.substring(17, 19);
        return dd;
    }

    /**
     *取系统当前时间:返回只值为如下形式
     *2002-10-30 20:24:39
     * @return String
     */
    public static String Now() {
        return dateToString(new Date());
    }

    /**
     *取系统当前时间:返回只值为如下形式
     *2002-10-30 08:28:56 下午
     *@param hour 为任意整数
     *@return String
     */
    public static String Now(int hour) {
        return dateToString(new Date(), hour);
    }
    /**
    *取系统当前时间:返回只值为如下形式
    *08:28:56
    *@return String
    */
    public static String NowCustom(String format) {
        return dateToStringCustom(new Date(),format);
    }


    /**
     *取系统当前时间:返回只值为如下形式
     *2002-10-30
     *@return String
     */
    public static String getYYYY_MM_DD() {
        return dateToString(new Date()).substring(0, 10);

    }

    /**
     *取系统当前时间:返回只值为如下形式
     *20021030
     *@return String
     */
    public static String getYYYYMMDD() {
        String L_curDate = cCharControl.getYYYY_MM_DD();
        String L_curDate2 = L_curDate.substring(0, 4) +
                            L_curDate.substring(5, 7) +
                            L_curDate.substring(8, 10);
        return L_curDate2;
    }
    /**
     *取系统当前时间:返回只值为如下形式
     *2002
     *@return String
     */
    public static String getYYYY() {
        String L_curDate = cCharControl.getYYYY_MM_DD();
        String L_curDate2 = L_curDate.substring(0, 4) ;       
        return L_curDate2;
    }
    /**
     *取系统当前时间:返回只值为如下形式
     *20021030
     *@return String
     */
    public static String getYYMMDD() {
        String L_curDate = cCharControl.getYYYY_MM_DD();
        String L_curDate2 = L_curDate.substring(2, 4) +
                            L_curDate.substring(5, 7) +
                            L_curDate.substring(8, 10);
        return L_curDate2;
    }

    /**
     * 对日期进行相加操作
     * @param date 日期字符串格式为yyyy-mm-dd
     * @param addNumber 要增加的天数
     * @return String 格式yyyy-mm-dd
     */
    public static String getDateAdd(String date, int addNumber) {
        String returnStr = "";
        StringTokenizer token = new StringTokenizer(date, "-");
        int num = token.countTokens();
        if (num == 3) {
            int year;
            int month;
            int day;
            year = Integer.parseInt(token.nextToken());
            month = Integer.parseInt(token.nextToken());
            day = Integer.parseInt(token.nextToken());
            SimpleDateFormat formatter;
            formatter = new SimpleDateFormat("yyyy-MM-dd");
            Calendar calen = Calendar.getInstance();
            calen.set(year, month - 1, day);
            calen.add(5, addNumber); //5代表日期,1代表年,2代表月
            returnStr = formatter.format(calen.getTime());
        } else {
            returnStr = date;
        }
        return returnStr;
    }
    /**
     * 对小时进行相加操作
     * @param date 日期字符串格式为yyyy-mm-dd
     * @param addNumber 要增加的小时数
     * @return String 格式yyyy-mm-dd
     */
    public static String getHourAdd(int addNumber) {
        String returnStr = "";
        SimpleDateFormat forma=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date dd=new Date();
        Calendar g=Calendar.getInstance();
        g.setTime(dd);
        g.add(Calendar.HOUR,addNumber);
        returnStr=forma.format(g.getTime());
        return returnStr;
    }

    /**
     *获得汉字的简拼码 wxx
     *2004-3-25
     *@return String
     */
    /*public  static String getSimpleSpell(String name){
        String ls_return,ls_jp;
        String ls_name,ls_temp;
        //例外处理
        if ((name==null) || (name.trim().length()==0))  return "";
        //初始化变量
        ls_return ="";
        ls_name = name;
        ls_jp="";
        ls_temp="";
        char  chatt;
        int itt=0;
        cDataControl cdcon=new cDataControl();//声明类
        for ( int i=0;i<ls_name.length();i++)
        {
          ls_temp=ls_name.substring(0,1);//
          chatt=ls_temp.charAt(0);
          itt=chatt;
          if (ls_name.length()>2){
          ls_name=ls_name.substring(1,ls_name.length());}//
          if (ls_temp==null) ls_temp ="";
           if (itt<128 ){  //小于128代表西文和数字>128代表汉字
             ls_jp = ls_temp;
           }else  if ( itt>128 ){
                 //从简拼表中获得简拼码
     ls_temp=pub.ViewControl.CharControl.cCharControl.Gb2312toISO(ls_temp);
           ls_jp=cdcon.GetFirfield("set rowcount 0 select jp from dict where name='"+ls_temp+"'");
           if (ls_jp==null) {ls_jp="";}
         }
         ls_return = ls_return+ls_jp;
        }
        cdcon.ReturnConn();//释放连接
        return ls_return;
      }*/
    /**
     *获得汉字的简拼码 wxx
     *2004-3-25
     *@return String
     */
    /*
     public  static String getSimpleSpellold(String name){
        String ls_return,ls_jp;
        String ls_name,ls_temp,ls_hz;
        int   ll_len;
        boolean lb_hz;

        //例外处理
        if ((name==null) || (name.trim().length()==0))  return "";
        //初始化变量
        ls_return ="";
        lb_hz = false;
        ls_name = name;
        ls_hz="";
        ls_jp="";
        cDataControl cdcon=new cDataControl();//声明类
        //生成简拼
        for (ll_len = 1;ll_len<name.length();)
        {        //得到汉字
          ls_temp = ls_name.substring(1,1);
           if (ls_temp==null) ls_temp ="";
              ls_name = ls_name.substring(2,ls_name.length());
              //半个汉字判断是否大于128
     if (( Integer.parseInt(ls_temp.getBytes().toString())>128 )&& (lb_hz==false)){
                lb_hz = true;
                ls_hz = ls_temp;
                ls_jp ="";
              }
              else if (( Integer.parseInt(ls_temp.getBytes().toString())>128 )&& (lb_hz==true)){
                ls_hz = ls_hz + ls_temp;
                 //从简拼表中获得简拼码
     ls_jp=cdcon.GetFirfield("select jp from dict where name='"+ls_hz+"'");
                 if (ls_jp==null) {ls_jp="";}
                 lb_hz = false;
              }else{
                lb_hz = false;
                ls_jp = ls_temp;
              }
             ls_return = ls_return+ls_jp;
        }
        cdcon.ReturnConn();//释放连接
        return ls_return;
      }

     /**
      *获得参数是奇数还是偶数 wxx
      *2004-4-5
      *返回0 代表偶数 ,-1代表 奇数
      */
     public static int isOddorEven(int iint) {
         int itmp = 0;
         try {
             itmp = iint % 2;
             if (itmp == 1) {
                 itmp = -1; //奇数
             }
             if (itmp == 0) {
                 itmp = 0; //偶数
             }
         } catch (Exception e) {
             itmp = -1;
         }
         return itmp;
     }

    /*************************************/
    //功能:转化为html语言输入数据库
    //方法:将字符窜中的
    //2005-12-30李胜修改:修改单引号(')的bug
    public static String HtmlToDB(String s) {
        s = Replace(s, "&", "&amp;");
        s = Replace(s, "\n", "<br>");
        s = Replace(s, "<", "&lt;");
        s = Replace(s, ">", "&gt;");
        s = Replace(s, "\t", "    ");
        s = Replace(s, "\r\n", "\n");
        s = Replace(s, " ", "&nbsp;");
        s=Replace(s, "'", "&single_qu");
        return s;
    }

    //功能:将数据库中的encode过的代码 输出 以td形式输出。
    //方法:
    public static String DBToHtml(String s) {
        s = Replace(s, "&amp", "&;");
        s = Replace(s, "&lt;", "<");
        s = Replace(s, "&gt;", ">");
        s = Replace(s, "    ", "\t");
        s = Replace(s, "\n", "\r\n");
        s = Replace(s, "<br>", "<br>");
        s = Replace(s, " &nbsp;", " &nbsp; ");
        s=Replace(s, "&single_qu", "'");
        return s;
    }

    //功能:修改显示时将数据库中的encode过的代码 输出 此时是多行文本框
    //方法:
    public static String HtmlWriteMX(String s) {
        s = Replace(s, "&amp", "&;");
        s = Replace(s, "&lt;", "<");
        s = Replace(s, "&gt;", ">");
        s = Replace(s, "    ", "\t");
        s = Replace(s, "\n", "\r\n");
        s = Replace(s, "<br>", "\n");
        s = Replace(s, "&nbsp;", " ");
        s=Replace(s, "&single_qu", "'");
        return s;
    }
    
    //2007-03-22  转换单引号为两个单引号,用于oracle查数据时单引号冲突! ---张瑞
    public static String InvertedCommaReplaceToDB(String s) {
        s=Replace(s, "'", "''");
        return s;
    }

    public static String Replace(
            String source,
            String oldString,
            String newString) {
        if (source == null) {
            return null;
        }
        StringBuffer output = new StringBuffer();
        int lengOfsource = source.length();
        int lengOfold = oldString.length();
        int posStart;
        int pos;
        for (posStart = 0; (pos = source.indexOf(oldString, posStart)) >= 0;
                                  posStart = pos + lengOfold) {
            output.append(source.substring(posStart, pos));
            output.append(newString);
        }

        if (posStart < lengOfsource) {
            output.append(source.substring(posStart));
        }
        return output.toString();
    }

    /*生成随即字符串*/
    public static String ProduceStr(int strLen) {
        if (strLen < 1) {
            return null;
        }
        if (strLen > 50) {
            strLen = 50;
        }
        String Vchar =
                "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUWXYZ";
        int Vlength = Vchar.length();
        char[] rchars = new char[strLen];
        for (int i = 0; i < strLen; i++) {
            rchars[i] = Vchar.charAt((int) (Math.random() * Vlength));
        }
        return String.valueOf(rchars);
    }

    /*
     *字符串查找,反回字符串要查找字符串前面有多少个字符
     *原字符串str
     *要查找的字符strfrom
     *原字符串中出现第几个ifrom
     */
    public static int formstr(String str, String strfrom, int ifrom) {
    int from = 0;
    int strfromlen = strfrom.length();
    for (int i = 0; i < ifrom; i++) {
        if (str.indexOf(strfrom, from) != -1) {
            from = str.indexOf(strfrom, from) + strfromlen;
        }
    }
    return from;
    }

    /*
     *返回当前日期是本月的第几周
     */
    public static String getWeek() {
    String week = "";
    Calendar calen = Calendar.getInstance();
    week=String.valueOf(calen.get(Calendar.WEEK_OF_MONTH));
    return week;
    }
    
/*判断对象类型的方法,柴振宁,2006-06-01*/
	
    /*检测某一对象是否是SortedMap对象的函数*/
	public boolean CheckSortedMap(Object obj){
		if(obj instanceof SortedMap){
			return true;
		}
		return false;
	}
	
	/*检测某一对象是否是List对象的函数*/
	public boolean CheckList(Object obj){
		if(obj instanceof List){
			return true;
		}
		return false;
	}
    
	/*检测某一对象是否是Map对象的函数*/
	public boolean CheckMap(Object obj){
		if(obj instanceof Map){
			return true;
		}
		return false;
	}
	/**
	*功能:将url地址转递进来的值进行转换(url 转换 数据)
	制作人:姚强强
	日期:2006-6-3*/
	public static String transUrlToData(String str){
		String temp=str;
		temp=replace(temp,"%2F","/");
		temp=replace(temp,"%26","&");
		temp=replace(temp,"%3F","?");
		temp=replace(temp,"%40","@");
		temp=replace(temp,"%23","#");
		temp=replace(temp,"%3B",";");
		temp=replace(temp,"%24","$");
		temp=replace(temp,"%2B","+");
		temp=replace(temp,"%3D","=");
		temp=replace(temp,"%25","%");
		return temp;
	}
	
	/**
	*功能:将url地址转递进来的值进行转换(数据 转换 url)
	制作人:张瑞
	日期:2007-08-21
	*/
	public static String transDataToUrl(String str){
		String temp=str;
		temp=replace(temp,"/","%2F");
		temp=replace(temp,"&","%26");
		temp=replace(temp,"?","%3F");
		temp=replace(temp,"@","%40");
		temp=replace(temp,"#","%23");
		temp=replace(temp,";","%3B");
		temp=replace(temp,"$","%24");
		temp=replace(temp,"+","%2B");
		temp=replace(temp,"=","%3D");
		temp=replace(temp,"%","%25");
		return temp;
	}
	
	/**判断整形*/
	public static boolean checkInt(String str){
		if(str!=null && str.matches("[\\d]+")){
			return true;
		}
		return false;
	}
	
    /**
     * 对日期进行相加操作(对月操作)
     * @param date 日期字符串格式为yyyy-mm-dd
     * @param addNumber 要月
     * @return String 格式yyyy-mm-dd
     */
    public static String getDateMonthAdd(String date, int addNumber) {
        String returnStr = "";
        StringTokenizer token = new StringTokenizer(date, "-");
        int num = token.countTokens();
        if (num == 3) {
            int year;
            int month;
            int day;
            year = Integer.parseInt(token.nextToken());
            month = Integer.parseInt(token.nextToken());
            day = Integer.parseInt(token.nextToken());
            SimpleDateFormat formatter;
            formatter = new SimpleDateFormat("yyyy-MM-dd");
            Calendar calen = Calendar.getInstance();
            calen.set(year, month - 1, day);
            calen.add(2, addNumber); //5代表日期,1代表年,2代表月
            returnStr = formatter.format(calen.getTime());
        } else {
            returnStr = date;
        }
        return returnStr;
    }	
    public static void main(String args[])
    {
    	System.out.println(cCharControl.Now());
    }
}

转载于:https://my.oschina.net/beer/blog/30075

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值