论坛首页 Java企业应用论坛

时间类型代码的参考

浏览 2290 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-09-02   最后修改:2010-04-09
public class SfUtil {
    public static final long hour = 60*60*1000l;            //一个小时

    public static final long oneday = 24*hour;              //一天


    public static String el(String str,int len){
        if(str==null) return "";
        if(len == -1) return str;
        if(str.length()<=len) return str;
        if(str.length()>len) return str.substring(0,len);
        return "";
    }

    /**
      * 显示按键
      * @param list
      * @return string
      */
     public String getButtom(List list){
         String button = "";
         for(int i=0;i<list.size();i++){
             Object[] obj = (Object[])list.get(i);
             button += htmlButton(obj) + "&nbsp;&nbsp";
         }
         return button;
     }

    private String htmlButton(Object[] obj){
         StringBuffer button = new StringBuffer();
         button.append("<input type=\"button\" name="+obj[0]+" value="+obj[1]+" onclick="+obj[2]+" id="+obj[3]+" ");
         button.append(" class=\"button\" onmousedown=\"this.className='button_down'\" onmouseout=\"if(this.className!='button') this.className='button';\" ");
         button.append(" onmouseover=\"if(this.className!='button_over') this.className='button_over';\" onfocus=\"this.blur();\">");
         return button.toString();
     }

    /**
     * 转为时间格式
     * @param dateStr  2007-10-3 20:00
     * @param format   yyyy-MM-dd HH:mm
     * @return  date
     */
    public static Date stringToDate(String dateStr,String format){
        java.text.SimpleDateFormat sf = new SimpleDateFormat(format);
        try {
            Date date = sf.parse(dateStr);
            return date;
        } catch (ParseException e) {
            return null;
        }
    }

    public static Timestamp stringToTimestamp(String dateStr,String format){
        if(format==null) format="yyyy-MM-dd HH:mm";
        Date date =  stringToDate(dateStr,format);
        return new Timestamp(date.getTime());
    }


    //取出上个月的当前时间
    public static Timestamp getlastMonthday(Timestamp time){
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(time.getTime());
        c.set(Calendar.DAY_OF_MONTH,c.get(Calendar.DAY_OF_MONTH)==31?c.get(Calendar.DAY_OF_MONTH)-1:c.get(Calendar.DAY_OF_MONTH));
        c.set(Calendar.MONTH,c.get(Calendar.MONTH)-1);

        return new Timestamp(c.getTime().getTime());
    }

    /**
     * 时间判断
     * @param t1    当前时间
     * @param t2    规写时间
     * @param day   天数
     * @return      boolean
     */
    public static boolean checkTimeBeweet(Timestamp t1,Timestamp t2,int day){
        long daylong = 24*hour;                   //一天时间
        long longt1 = t1.getTime();
        long longt2 = t2.getTime();
        System.out.println(""+(Math.abs(longt2-longt1)-daylong*day));

        return Math.abs(longt2-longt1)-daylong*day>0;
    }


    /**
     *转换为时间格式
     * @param time
     * @param i
     * @return  string
     */
   public static String getDateFormat(Timestamp time,int i){
       if(time==null) return "";
       String format = "yyyy-MM-dd";
       switch(i){
           case 1:format="yyyy-MM-dd";break;
           case 2:format="yyyy-MM-dd HH:mm";break;
           case 3:format="HH点mm分";break;
           case 4:format="yyyy年MM月dd日 HH点mm分";break;
           case 5:format="yyyyMMdd";break;
           case 6:format="yyyy年MM月dd日";break;
           case 7:format="yyyyMMdd";break;
           case 8:format="MM月dd日 HH点mm分";break;
           case 9:format="MM-dd HH:mm";break;
           case 10:format="MM月dd日";break;
           case 11:format=" HH:mm";break;
           case 12:format="yyyy";break;
           case 13:format="MM-dd";break;
           case 14:format="yyyyMM";break;
           case 15:format="yyyy-MM-dd hh:mm";break;
           case 16:format="yy-MMdd hh:mm";break;
           case 17:format="yyyyMMddHH";break;
           case 18:format="HH";break;
           default: format = "yyyy-MM-dd";break;
       }
       SimpleDateFormat sdf = new SimpleDateFormat(format);
       return sdf.format(time);
   }


    /**
      * 一个月的第一天
      * @param time
      * @return
      */
     public static Timestamp startOfMonth(Timestamp time){
        time.setDate(1);
        time.setHours(0);
        time.setMinutes(0);
        time.setSeconds(0);
        return time;
     }

    /**
     * 功能: 一月中的最后一天.
     * 输入: time = 给出的当周内的某一天.
     *  输出: 该周的最后一天.
     * @param time
     * @return
     */
    public static Timestamp endOfMonth(Timestamp time){
          time.setDate(DaysInMonth(time));
          return time;
     }

    /**
     * 功能: 当月的天数.
     * 输入: month = 给出的该月的某一个时间.
     * 输出:  这个月有多少天.
     *
     * @param time
     * @return
     */
    public static int DaysInMonth(Timestamp time){
        int month=time.getMonth();
        int year=time.getYear();
        int DaysInMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        if(month==1){
            if(IsLeapYear(year+1900))
                DaysInMonth[1]= DaysInMonth[1]+1;
        }
        return DaysInMonth[month];
    }

    /**
     * 功能: 判断是否是闰年.
     * 输入: year = 给出的 1582 年以后的年份
     * 输出: TRUE 是闰年, FALSE 不是..
     *
     * 能被100整除, 不能被400整除的年份, 不是闰年.
     * 能被100整除, 也能被400整除的年份, 是闰年.
     * 不能被100整除, 能被4整除的年份是闰年.
     * @param year
     * @return
     */
    public static boolean IsLeapYear(int year){
       if ((year % 100) == 0) return((year % 400) == 0);
       return ((year % 4) == 0);
    }

    /**
     * 半角转全角
     * @param QJstr
     * @return
     */
    public static final String BQchange(String QJstr) {
        String outStr = "";
        String Tstr = "";
        byte[] b = null;

        for (int i = 0; i < QJstr.length(); i++) {
            try {
                Tstr = QJstr.substring(i, i + 1);
                b = Tstr.getBytes("unicode");
            } catch (java.io.UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            if (b[3] != -1) {
                b[2] = (byte) (b[2] - 32);
                b[3] = -1;
                try {
                    outStr = outStr + new String(b, "unicode");
                } catch (java.io.UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            } else
                outStr = outStr + Tstr;
        }

        return outStr;
    }



    /**
     * 全角转半角
     * @param QJstr
     * @return string
     */
    public static final String QBchange(String QJstr) {
        String outStr = "";
        String Tstr = "";
        byte[] b = null;

        for (int i = 0; i < QJstr.length(); i++) {
            try {
                Tstr = QJstr.substring(i, i + 1);
                b = Tstr.getBytes("unicode");
            } catch (java.io.UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            if (b[3] == -1) {
                b[2] = (byte) (b[2] + 32);
                b[3] = 0;
                try {
                    outStr = outStr + new String(b, "unicode");
                } catch (java.io.UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            } else
                outStr = outStr + Tstr;
        }

        return outStr;
    }


    private static String encoderString = "w123abcd48STGX0UVWYHIJ5fghijklmnstuvBCDEF67KL9AeQRMNopqrOPxyzZ&*%$@!><";
    private static String encodeWord(String word){
        int pos = encoderString.indexOf(word);
        if(pos==-1)return word;
        pos = 10+pos;
        pos = pos%encoderString.length();
        return encoderString.substring(pos,pos+1);
    }

    private static String deEncodeWord(String word){
        int pos = encoderString.indexOf(word);
        if(pos==-1)return word;
        pos = encoderString.length()+pos-10;
        pos = pos%encoderString.length();
        return encoderString.substring(pos,pos+1);
    }

    public static final String IdTran = "adkkjasdf0988231273664767123hhjasdhfhyuehadssfnxjaufeaeh12";
    public static final String PwdTran = "adkkjasdfaoopadfjue1273664767123hhjasdhfhyuehadssfnxjaufeaeh12";

    //加密
    public static String tranValueEncode(String str){
        StringBuffer sb = new StringBuffer("");
        for(int i=0;i<str.length();i++){
            String ch = str.substring(i,i+1);
            sb.append(encodeWord(ch));
        }
        return sb.toString();
    }

    //解密
    public static String stanValueDeEncode(String str){
        StringBuffer sb = new StringBuffer("");
        for(int i=0;i<str.length();i++){
            String ch = str.substring(i,i+1);
            sb.append(deEncodeWord(ch));
        }
        return sb.toString();
    }


    /**
     * 取出上半年或下半年
     * @param time
     * @return string
     */
    public static String getYearhalf(Timestamp time){
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(System.currentTimeMillis());
        String year = cal.get(Calendar.YEAR)+"";
        if(time==null) return year+"06";
        String ds = year+"-06-01 00:00";
        String format = "yyyy-MM-dd HH:mm";
        Timestamp t = new Timestamp(stringToDate(ds,format).getTime());
        if(t.equals(time)||t.after(time)) return year+"06";
        else return year+"07";

    }

    public static String getWeek(int year,int month,int day){
       Calendar C =  Calendar.getInstance();
       C.set(year,month-1,day,0,0,0);

       int week = C.get(Calendar.DAY_OF_WEEK);
       String weekStr = "";
       switch(week){
           case 1:
               weekStr = "星期天";
               break;
            case 2:
               weekStr = "星期一";
               break;
            case 3:
               weekStr = "星期二";
               break;
            case 4:
               weekStr = "星期三";
               break;
            case 5:
               weekStr = "星期四";
               break;
            case 6:
               weekStr = "星期五";
               break;
            case 7:
               weekStr = "星期六";
               break;
       }
       return weekStr;
   }

    /**
     * 取昨天
     * @param today (格式:20070902)
     * @param i
     * @return
     */
    public static String getYesterdayByToday(String today,int i,int next){
        String yesterdayByToday = "";
        String yy = today.substring(0,4);
        String mm = "";
        String dd = "";
        mm=today.substring(4,5);
        if(mm.equals("0")){
            mm=today.substring(5,6);
        }else{
            mm = today.substring(4,6);
        }
        dd=today.substring(6,7);
        if(dd.equals("0")){
            dd=today.substring(7,8);
        }else{
            dd=today.substring(6,8);
        }
        int yy1 = Integer.parseInt(yy);
        int mm1 = Integer.parseInt(mm);
        int dd1 = Integer.parseInt(dd);

        int[] yesterday =  getBeforeDate(yy1,mm1,dd1,next);
        int yy2 = yesterday[0];
        int mm2 = yesterday[1];
        int dd2 = yesterday[2];
        String mm3 = ""+mm2;
        if(mm3.length()<2){
            mm3 = "0"+mm3;
        }
        String dd3 = ""+dd2;
        if(dd3.length()<2){
            dd3 = "0"+dd3;
        }
        switch(i){
            case 1:
                yesterdayByToday = yy2+"-"+mm3+"-"+dd3;
                break;
            case 2:
                yesterdayByToday = yy2+mm3+dd3;
                break;
            default:
                yesterdayByToday = yy2+"-"+mm3+"-"+dd3;
        }
        return yesterdayByToday;
    }

    /**
     * 得到某一个日期的前面的日期,返回为一个一维数组,有3个元素,分别为年、月、日
     * @param year
     * @param month
     * @param day
     * @param beforeDays
     * @return
     */
    public static int[] getBeforeDate(int year,int month,int day,int beforeDays){
        Calendar C =  Calendar.getInstance();
        C.set(year,month-1,day,0,0,0);
        C.add(Calendar.DATE,beforeDays*(-1));
        int y = C.get(Calendar.YEAR);
        int m = C.get(Calendar.MONTH)+1;
        int d = C.get(Calendar.DATE);
        int[] a = new int[3];
        a[0] = y;
        a[1] = m;
        a[2] = d;
        return a;
    }


    public static String showNumber(String number,String format){
        if(number==null) return "";
        if(format == null) format = "#.##";
        double datanumber = Double.parseDouble(number);
        java.text.NumberFormat nf = new DecimalFormat(format);
        return nf.format(datanumber);
    }

    public static String showNumber(float number,String format){
        if(number==0.0) return "0.0";
        if(format == null) format = "#.##";
        //float datanumber = number;
        java.text.NumberFormat nf = new DecimalFormat(format);
        return nf.format(number);
    }

    /**
    * 获取给定时间所在月的第一天F的日期和最后一天的日期   *
    * @param date
    * @return Date数组,[0]为第一天的日期,[1]最后一天的日期
    */

    public static Date[] getMonthStartAndEndDate(Date date) {
        Date[] dates = new Date[2];
        Date firstDateOfMonth, lastDateOfMonth;
        // 得到当天是这月的第几天
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
        // 减去dayOfMonth,得到第一天的日期,因为Calendar用0代表每月的第一天,所以要减一
        calendar.add(Calendar.DAY_OF_MONTH, -(dayOfMonth - 1));
        calendar.set(Calendar.HOUR_OF_DAY,0);
        calendar.set(Calendar.MINUTE,0);
        calendar.set(Calendar.SECOND,0);
        calendar.set(Calendar.MILLISECOND,0);
        firstDateOfMonth = calendar.getTime();
        // calendar.getActualMaximum(Calendar.DAY_OF_MONTH)得到这个月有几天
        calendar.add(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH) - 1);
        calendar.set(Calendar.HOUR_OF_DAY,23);
        calendar.set(Calendar.MINUTE,59);
        calendar.set(Calendar.SECOND,59);
        calendar.set(Calendar.MILLISECOND,99);
        lastDateOfMonth = calendar.getTime();

        dates[0] = firstDateOfMonth;
        dates[1] = lastDateOfMonth;
        return dates;
    }

    public static Date getDayBetweeb(Date date,int day,int minute){
         Calendar C = Calendar.getInstance();
         C.setTime(date);
         C.set(Calendar.HOUR_OF_DAY,day);
         C.set(Calendar.MINUTE,minute);
         C.set(Calendar.SECOND,0);
         C.set(Calendar.MILLISECOND,0);

         return C.getTime();
    }

    /**
     * 得到某一天的开始时刻和结束时刻
     * @param date
     * @return
     */
    public static Date[] getDayStartAndEndDate(Date date){
        Date[] dates = new Date[2];
        Calendar C = Calendar.getInstance();
        C.setTime(date);
        C.set(Calendar.HOUR_OF_DAY,0);
        C.set(Calendar.MINUTE,0);
        C.set(Calendar.SECOND,0);
        C.set(Calendar.MILLISECOND,0);
        dates[0] = C.getTime();
        C.set(Calendar.HOUR_OF_DAY,23);
        C.set(Calendar.MINUTE,59);
        C.set(Calendar.SECOND,59);
        C.set(Calendar.MILLISECOND,99);
        dates[1] = C.getTime();
        return dates;
    }

    /**
     * 20040806 ---->2005-08-06
     * @param DB_declaredTime
     * @return
     */
     public static String getChange(String DB_declaredTime,int i){
        String changeTime = "";
        String y1=DB_declaredTime.substring(0,4);
        String m1=DB_declaredTime.substring(4,6);
        String d1=DB_declaredTime.substring(6,8);
        if(i==1) changeTime = y1+"年"+m1+"月"+d1+"日";
        else changeTime = y1+"-"+m1+"-"+d1;
        return changeTime;
     }

    //计算明天(-1)
    public static Timestamp TimestampTo(Timestamp time,int next){
        if(time == null) time = new Timestamp(System.currentTimeMillis());
        String str = getDateFormat(time,5);

        return stringToTimestamp(getYesterdayByToday(str,1,next)+" 00:00",null);
    }

    //当前时间,返回一天的开始时间(1)和结束时间(2)
    public static Timestamp getDayTime(Timestamp time,int local){
        Date[] date = getDayStartAndEndDate(time);
        Date dtime = null;
        switch(local){
            case 1: dtime = date[0];break;
            case 2: dtime = date[1];break;
            default:dtime = date[0];break;
        }
        return dtime==null?new Timestamp(System.currentTimeMillis()):new Timestamp(dtime.getTime());
    }

    /**
     * 将文件名中的汉字转为UTF8编码的串,以便下载时能正确显示另存的文件名.
     * @param s 原文件名
     * @return 重新编码后的文件名
     */
    public static String toUtf8String(String s) {
        StringBuffer sb = new StringBuffer();
        for (int i=0;i<s.length();i++) {
            char c = s.charAt(i);
            if (c >= 0 && c <= 255) {
                sb.append(c);
            } else {
                byte[] b;
                try {
                    b = Character.toString(c).getBytes("utf-8");
                } catch (Exception ex) {
                    System.out.println(ex);
                    b = new byte[0];
                }
                for (int j = 0; j < b.length; j++) {
                    int k = b[j];
                    if (k < 0) k += 256;
                    sb.append("%" + Integer.toHexString(k).
                    toUpperCase());
                }
            }
        }
        return sb.toString();
    }

    public static String asciiToUnicode(String source){
        Pattern pattern = Pattern.compile("\\\\u(\\p{XDigit}{4})");
        java.util.regex.Matcher matcher = pattern.matcher(source);
        StringBuffer buf = new StringBuffer(200);
        System.out.println(""+matcher.groupCount());
        while (matcher.find()) {
          char ch = (char) Integer.parseInt(matcher.group(1), 16);
            System.out.println(""+ch);
          buf.append(ch);
        }

        return buf.toString();
      }

    //取整数(两个时间相减)
    public static String getItemnumber(String number){                              
        if(number==null||number.length()==0) return "1";
        float f = Float.valueOf(number);
        return new Double(Math.ceil(f)).intValue()+"";
    }

    //取季度的开始时间和结束时间
    public static Date[] getQuarter(int year,int quarter){
        int monthst = 1;
        int monthet = 3;
        switch(quarter){
            case 2:{monthst = 4;monthet=6;break;}
            case 3:{monthst = 7;monthet=9;break;}
            case 4:{monthst = 10;monthet=12;break;}
            case 6:{monthst = 1;monthet=6;break;}         //上半年
            case 12:{monthst = 7;monthet=12;break;}       //下半年
            default:{monthst=1;monthet=3;break;}
        }
        Calendar cal = Calendar.getInstance();
        cal.set(year,monthst-1,1);
        Date[] date1 = getMonthStartAndEndDate(cal.getTime());

        cal.set(year,monthet-1,1);
        Date[] date2 = getMonthStartAndEndDate(cal.getTime());

        return new Date[]{date1[0],date2[1]};
    }

    //取出两个时间之间的天数
    public static List getBetweebTimes(String startstr,String endstr,int index){
        Timestamp startTime = null;
        Timestamp endTime = null;

        Timestamp currtime = new Timestamp(System.currentTimeMillis());
        Timestamp beforeDate = SfUtil.TimestampTo(currtime,1);//取昨天日期
        if(startstr==null&&endstr==null){
            startTime = SfUtil.TimestampTo(currtime,15);
            endTime = beforeDate;
        }else{
            if(startstr!=null){
                startstr = startstr + " 00:00";
                startTime = SfUtil.stringToTimestamp(startstr,null);
                if(endstr==null) endTime = beforeDate;
            }
            if(endstr!=null){
                endstr = endstr + " 00:00";
                endTime = SfUtil.stringToTimestamp(endstr,null);
                if(startstr == null) startTime = SfUtil.TimestampTo(currtime,15);
            }
        }

        return getTimeBetweeb(startTime,endTime,index);
    }

    //取出两个时间之间的天数(按不同的格式)
    public static List getTimeBetweeb(Timestamp startTime,Timestamp endTime,int index){
        long MS_SECOND =  1000;
        long MS_MINUTE =  60 * MS_SECOND;
        long MS_HOUR =    60 * MS_MINUTE ;
        long MS_DAY =     24 * MS_HOUR;

        startTime = getDayTime(startTime,1);
        endTime = getDayTime(endTime,1);

        System.out.println("startTime == "+startTime);
        System.out.println("endTime == "+endTime);

        java.util.Date start = startTime;
        java.util.Date end = endTime;
        List days = new ArrayList();

        for(java.util.Date d=start;!d.after(end)||d.equals(end);){
            Timestamp time = new Timestamp(d.getTime());
            String yyyymmdd = getDateFormat(time,index);
            days.add(yyyymmdd);
            d = new java.util.Date(d.getTime() + MS_DAY);
        }
        return days;
    }


    public static void main(String[] args){
        /*Timestamp time = stringToTimestamp("2008-06-01 00:00",null);
        Timestamp time1 = getlastMonthday(time);
        System.out.println(""+time1);
        Date[] dates = getMonthStartAndEndDate(time);
        System.out.println(""+new Timestamp(dates[0].getTime()));
        System.out.println(""+new Timestamp(dates[1].getTime()));*/

        /*Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(System.currentTimeMillis());
        System.out.println(""+cal.get(Calendar.YEAR));
        System.out.println(""+(cal.get(Calendar.MONTH)+1));
        */
        /*Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(System.currentTimeMillis());
        for(int i=0;i<38;i++){
            cal.set(Calendar.DATE,Calendar.DAY_OF_WEEK+i);
            System.out.println(""+new Timestamp(cal.getTimeInMillis()));
        }*/

        //Timestamp today = new Timestamp(System.currentTimeMillis());
        //String str = getDateFormat(today,5);

        //System.out.println(str + "  "+stringToTimestamp(getYesterdayByToday(str,1,-1)+" 00:00",null));
        //System.out.println(""+new Timestamp(getDayBetweeb(today,19,40).getTime()));

        String abb = "妇女的典范\\u2014\\u2014符桂花同志的优秀事迹";

        String abc = "国防大学\"成功\"研究成功!";

        //abb = java.net.URLEncoder.encode(abb);
        //abb = java.net.URLDecoder.decode(abb);
        //String abb1 = asciiToUnicode(abb);

        System.out.println(""+abc.replaceAll("\"","“").replaceAll("\"","”"));
        System.out.println("全角转半角 === "+QBchange(abc));
        System.out.println("半角转全角 === "+BQchange(abc));

        System.out.println(""+new Double(Math.ceil(Float.valueOf(10.5315972222222f))).intValue());
        System.out.println(""+getItemnumber("-10.5315972222222"));

        System.out.println(""+stanValueDeEncode("gggggHrr"));

        System.out.println(""+TimestampTo(null,1));

        /*SfUtil u = new SfUtil();
        Object[] obj = u.getBetweebTimes("2008-08-28","2008-08-28",7);
        for(int i=0;i<obj.length;i++){
            System.out.println("obj === "+obj[i]);
        }
        */

        Date[] date = getQuarter(2008,12);
        System.out.println(" "+new Timestamp(date[0].getTime()));
        System.out.println(" "+new Timestamp(date[1].getTime()));

    }

}

 

论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics