java日期處理工具類

import java.text.DecimalFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.Vector;
public class DateUtil
{
    public static final String DEFAULT_DATE_FORMAT = "MM-dd-yyyy";
    public static final String ZH_DATE_FORMAT = "yyyy-MM-dd";
    public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";
    public static final String DEFAULT_DATETIME_FORMAT = "MM-dd-yyyy HH:mm:ss";
    public static final String ZH_DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    public static final String DEFAULT_PRECISION_DATETIME_FORMAT = "MM-dd-yyyy HH:mm:ss:SSS";
    public static final String ZH_PRECISION_DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss:SSS";
    public static final String DEFAULT_PRECISION_MILLTIME_FORMAT = "yyyy:MM:dd HH:mm:ss:SSS";
    public static final String DEFAULT_HOUR_DATE_FORMAT = "MM-dd-yyyy HH";
    public static final String ZH_HOUR_DATE_FORMAT = "yyyy-MM-dd HH";
    public static final String DEFAULT_MINUTE_DATE_FORMAT = "MM-dd-yyyy HH:mm";
    public static final String ZH_MINUTE_DATE_FORMAT = "yyyy-MM-dd HH:mm";
    public static final String ZH_SECOND_DATE_FORMAT = "yyyyMMddHHmmss";
    /**
     * 日期時間格式1-"yyyy.MM.dd HH:mm:ss"
     */
    public static final String TIMEFORMAT_FULL = "yyyy.MM.dd HH:mm:ss";
    /**
     * 日期時間格式2-"yyyy.MM.dd HH:mm"
     */
    public static final String TIMEFORMAT_NO_SEC = "yyyy.MM.dd HH:mm";
    /**
     * 日期格式1-"yyyy.MM.dd"
     */
    public static final String TIMEFORMAT_NO_TIME = "yyyy.MM.dd";
    /**
     * 日期格式2-"yyyy.MM"
     */
    public static final String TIMEFORMAT_YEAR_MONTH_ONLY = "yyyy.MM";
    /**
     * 日期格式3-"yyyyMMdd"
     */
    public static final String TIMEFORMAT_ANOTHER_DATE = "yyyyMMdd";
    /**
     * 1024以內的素數表,172個
     */
    public static int sNumprime[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73,
            79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191,
            193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311,
            313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439,
            443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577,
            587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709,
            719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857,
            859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997, 1009,
            1013, 1019, 1021 };
    /**
     * 構造函數
     */
    public DateUtil()
    {
    }
    /**
     * 按日期時間格式1返回當前時間 yyyy.MM.dd HH:mm:ss
     * 
     * @return String 獲得當前時間
     */
    public static String getCurrentDateTime()
    {
        SimpleDateFormat sdf = new SimpleDateFormat(TIMEFORMAT_FULL);
        return sdf.format(new Date());
    }
    
    public static String getCurrentDateTime_14()
    {
        SimpleDateFormat sdf = new SimpleDateFormat(ZH_SECOND_DATE_FORMAT);
        return sdf.format(new Date());
    }
    /**
     * 按日期格式1返回當前日期
     * 
     * @return String 獲得當前日期
     */
    public static String getCurrentDate()
    {
        SimpleDateFormat sdf = new SimpleDateFormat(TIMEFORMAT_NO_TIME, Locale.US);
        return sdf.format(new Date());
    }
    /**
     * 按日期格式3返回數字日期
     * 
     * @return String 獲得數字日期
     */
    public static String getPiciDate()
    {
        SimpleDateFormat sdf = new SimpleDateFormat(TIMEFORMAT_ANOTHER_DATE, Locale.US);
        return sdf.format(new Date());
    }
    /**
     * 按日期格式3返回數字日期
     * 
     * @param sNowDateTime 設置時間,格式爲YYYYMMDDHH24MISS
     */
    public static void setCurrentDate(String sNowDateTime)
    {
        if (sNowDateTime.length() == 14)
        {
            int iyear;
            int imonth;
            int idate;
            int ihour;
            int iminute;
            int isecond;
            iyear = java.lang.Integer.parseInt(sNowDateTime.substring(0, 4));
            if (iyear < 2000)
            {
                iyear = 2003;
            }
            imonth = java.lang.Integer.parseInt(sNowDateTime.substring(4, 6));
            if (imonth > 12)
            {
                imonth = 11;
            }
            idate = java.lang.Integer.parseInt(sNowDateTime.substring(6, 8));
            if (idate > 31)
            {
                idate = 11;
            }
            ihour = java.lang.Integer.parseInt(sNowDateTime.substring(8, 10));
            if (ihour > 23)
            {
                ihour = 11;
            }
            iminute = java.lang.Integer.parseInt(sNowDateTime.substring(10, 12));
            if (iminute > 59)
            {
                iminute = 11;
            }
            isecond = java.lang.Integer.parseInt(sNowDateTime.substring(12, 14));
            if (isecond > 59)
            {
                isecond = 11;
            }
            Calendar serverNow = Calendar.getInstance();
            serverNow.set(iyear, imonth, idate, ihour, iminute, isecond);
        }
    }
    /**
     * Function name: sGetAddTimes Description: 給一個時間增加上一定的時間
     * 
     * @param timePoint 計時時間點(格式:TimeFormat1)
     * @param addSeconds times to add(單位:秒)
     * @return String 返回增加時間後的時間(格式:TimeFormat1)
     */
    public static String sGetAddTimes(String timePoint, long addSeconds)
    {
        if (timePoint.length() == 19)
        {
            String dRet = "";
            SimpleDateFormat sdf = new SimpleDateFormat(TIMEFORMAT_FULL);
            Date timePoints = sdf.parse(timePoint, new java.text.ParsePosition(0));
            Date dateTimes = new Date((timePoints.getTime() / 1000L + (addSeconds)) * 1000L);
            dRet = sdf.format(dateTimes);
            return dRet;
        }
        else
        {
            return "";
        }
    }
    /**
     * Function name: sGetAddTimes Description: 給一個時間減去上一定的時間
     * 
     * @param timePoint 計時時間點(格式:TimeFormat1)
     * @param addSeconds times to add(單位:秒)
     * @return String 返回減去時間後的時間(格式:TimeFormat1)
     */
    public static String sGetMinusTimes(String timePoint, long minusSeconds)
    {
        if (timePoint.length() == 19)
        {
            String dRet = "";
            SimpleDateFormat sdf = new SimpleDateFormat(TIMEFORMAT_FULL);
            Date timePoints = sdf.parse(timePoint, new java.text.ParsePosition(0));
            Date dateTimes = new Date((timePoints.getTime() / 1000L - (minusSeconds)) * 1000L);
            dRet = sdf.format(dateTimes);
            return dRet;
        }
        else
        {
            return "";
        }
    }
    /**
     * Function name: lTimeCompare Description: 兩時間比較. Compare two times
     * 
     * @param compTime1 比較時間1(格式:TimeFormat1)
     * @param compTime2 比較時間2(格式:TimeFormat1)
     * @return long 返回相差的時間(單位:秒)
     */
    public static long lTimeCompare(String compTime1, String compTime2)
    {
        if ((compTime1.length() == 19) && (compTime2.length() == 19))
        {
            long iReturn = -1;
            SimpleDateFormat sdf = new SimpleDateFormat(TIMEFORMAT_FULL);
            Date dateTime1 = sdf.parse(compTime1, new java.text.ParsePosition(0));
            Date dateTime2 = sdf.parse(compTime2, new java.text.ParsePosition(0));
            iReturn = dateTime2.getTime() / 1000L - dateTime1.getTime() / 1000L;
            return iReturn;
        }
        else
        {
            return 0;
        }
    }
    /**
     * Function name: lTimeCompareNow Description: 與當前時間比較. Compare one time
     * with now
     * 
     * @param compTime1 比較時間1(格式:TimeFormat1)
     * @return long 返回相差的時間(單位:秒)
     */
    public static long lTimeCompareNow(String compTime1)
    {
        if (compTime1 != null && compTime1.equals("999"))
        {
            return -1;
        }
        if (compTime1.length() == 19 || compTime1.length() == 10)
        {
            long iReturn = -1;
            if (compTime1.length() == 10)
            {
                compTime1 += " 00:00:00";
            }
            SimpleDateFormat sdf = new SimpleDateFormat(TIMEFORMAT_FULL);
            Date dateTime1 = sdf.parse(compTime1, new java.text.ParsePosition(0));
            iReturn = java.lang.System.currentTimeMillis() / 1000L - dateTime1.getTime() / 1000L;
            return iReturn;
        }
        else
        {
            return 0;
        }
    }
    /**
     * Function name: fmtDate Description: 日期字符串規範化. format a date string using
     * comm
     * 
     * @param sDate 要規範的日期字符串(如2003-11-11、2003/11/11)
     * @param comm 日期字符串中間的分隔符
     * @return String 返回規範化後的字符串
     */
    public static String fmtDate(String sDate, String comm)
    {
        String dRet = "";
        if (sDate.length() == 10)
        {
        }
        else
        {
            sDate = getCurrentDate();
        }
        dRet = sDate.substring(0, 4) + comm + sDate.substring(5, 7) + comm + sDate.substring(8, 10);
        return dRet;
    }
    /**
     * Function name: fmtDateTime Description: 日期時間字符串規範化. format a date string
     * using comm
     * 
     * @param sDate 要規範的日期時間字符串(如2003-11-11 11:11:11、2003/11/11 11:11:11)
     * @param comm 日期中間的分隔符
     * @return String 返回規範化後的字符串
     */
    public static String fmtDateTime(String sDate, String comm)
    {
        String dRet = "";
        if (sDate.length() == 19)
        {
        }
        else
        {
            sDate = getCurrentDateTime();
        }
        dRet = sDate.substring(0, 4) + comm + sDate.substring(5, 7) + comm + sDate.substring(8, 10) + " "
                + sDate.substring(11, 13) + ":" + sDate.substring(14, 16) + ":" + sDate.substring(17, 19);
        return dRet;
    }
    /**
     * Function Name: SubStr Description: 取指定長度的字符子串,超過取到串尾
     * 
     * @param fullString 源字符串
     * @param nStart 開始字節
     * @param nLen 要取的長度
     * @return String 返回目的字符串
     */
    public static String subStr(String fullString, int nStart, int nLen)
    {
        String sResult = "";
        if ((nStart + nLen) > fullString.length())
        {
            sResult = fullString.substring(nStart);
        }
        else
        {
            sResult = fullString.substring(nStart, (nStart + nLen));
        }
        return sResult;
    }
    /**
     * Function Name: DevideStr Description: 分解字符串
     * 
     * @param fullString 源字符串
     * @param sComm 字符串中間的分隔符
     * @return Vector 返回分解後的字符串列
     */
    public static Vector<String> devideStr(String fullString, String sComm)
    {
        Vector<String> vTmp = new Vector<String>();
        try
        {
            if (sComm.length() > 1)
            {
                sComm = sComm.substring(0, 1);
            }
            StringTokenizer stString = new StringTokenizer(fullString, sComm);
            while (stString.hasMoreTokens())
            {
                vTmp.addElement(stString.nextToken());
            }
        }
        catch (Exception e)
        {
            vTmp.clear();
        }
        return vTmp;
    }
    /**
     * Function Name: DivideCSV Description: 分解CSV格式字符串
     * 
     * @param fullString 源字符串
     * @param sComm 字符串中間的分隔符
     * @return Vector 返回分解後的字符串列
     * @see #devideStr(String, String) deprecated 由DevideStr(String,
     *      String)函數替代,該函數不再使用。
     */
    public static Vector<String> divideCSV(String fullString, String sComm)
    {
        Vector<String> vTmp = new Vector<String>();
        if (sComm.length() > 1)
        {
            sComm = sComm.substring(0, 1);
        }
        StringTokenizer stString = new StringTokenizer(fullString, sComm);
        while (stString.hasMoreTokens())
        {
            vTmp.addElement(stString.nextToken());
        }
        return vTmp;
    }
    /**
     * Function Name: GenRandom Description: 隨機數產生程序
     * 
     * @param nIn 隨機數種子
     * @param nLen 隨機數長度
     * @return String 返回隨機數
     */
    public static String genRandom(int nIn, int nLen)
    {
        int nYear;
        int nMonth;
        int nDay;
        int nHour;
        int nSec;
        int nMsec;
        double f1;
        double f2;
        long temp;
        int count;
        int loopCount;
        int i;
        int rest;
        String sResult = "";
        String sFull = "";
        if (nLen > 9)
        {
            loopCount = nLen / 9;
            for (i = 1; i <= loopCount; i++)
            {
                sResult = sResult + genRandom(i, 9);
            }
            rest = nLen - loopCount * 9;
            if (rest != 0)
            {
                sResult = sResult + genRandom(1, rest);
            }
        }
        else
        {
            if (nLen == 0)
            {
                return "";
            }
            sFull = "";
            for (count = 1; count <= nLen; count++)
            {
                sFull = sFull + "0";
            }
            DecimalFormat nf = new DecimalFormat(sFull);
            Calendar nowTime = Calendar.getInstance();
            nYear = nowTime.get(Calendar.YEAR);
            nMonth = nowTime.get(Calendar.MONTH) + 1;
            nDay = nowTime.get(Calendar.DAY_OF_MONTH);
            nHour = nowTime.get(Calendar.HOUR_OF_DAY);
            nSec = nowTime.get(Calendar.SECOND);
            nMsec = nowTime.get(Calendar.MILLISECOND);
            f2 = Math.sin(Math.sqrt((nIn % 713) + nMsec + nSec * 34 + nHour * 47) + nMsec * nSec * nHour);
            f1 = Math.pow((Math.abs(f2 * 89 + 79 * Math.cos(nIn + nMsec * nSec)) * 31), 2);
            temp = (long) f1 + nIn + nYear + nMonth * 11 + nDay;
            StringBuffer stemp = new StringBuffer((new java.lang.Long(temp)).toString());
            stemp = stemp.reverse();
            Random rd = new Random();
            rd.setSeed(java.lang.Long.parseLong(stemp.toString()) + (nIn % 3));
            sResult = nf.format(rd.nextInt((int) (Math.pow(10, nLen) - 1)));
        }
        return sResult;
    }
    /**
     * Function Name: VarlenRnd Description: 取可變長隨機數,長度範圍由參數指定
     * 
     * @param minLen 最小長度
     * @param maxLen 最大長度
     * @return String 返回隨機數
     */
    public static String varlenRnd(int minLen, int maxLen)
    {
        String sResult = "";
        if (minLen < maxLen)
        {
            int nLen = java.lang.Integer.parseInt(genRandom(3, 1)) % (maxLen - minLen + 1) + minLen;
            sResult = genRandom(3, nLen);
        }
        else
        {
            sResult = genRandom(3, maxLen);
        }
        return sResult;
    }
    /**
     * BCD碼左對齊轉字符串
     * 
     * @param bcd 你一次讀進的字節數,因爲可能會大於你要處理的字節數
     * @param begin 字節開始位置
     * @param length 字節長,與begin一起決定真正要處理的字節數
     * @return String 返回對齊後字符串
     */
    public static String bcd2Str(byte[] bcd, int begin, int length)
    {
        String str = "";
        int temp;
        for (int i = begin; i < begin + length; i++)
        {
            if (bcd[i] == 0)
            {
                break;
            }
            temp = (bcd[i] & 0x0F) % 10;
            str += temp;
            temp = (bcd[i] >>> 4) % 10;
            if (bcd[i] >>> 4 != 0)
            {
                str += temp;
            }
        }
        return str;
    }
    /**
     * 普通的二進制轉字串
     * 
     * @param hex 你一次讀進的字節數,因爲可能會大於你要處理的字節數
     * @param begin 字節開始位置
     * @param num 字節長,與begin一起決定真正要處理的字節數
     * @return String 返回轉換後字符串
     */
    public static String hex2Str(byte[] hex, int begin, int num)
    {
        String overflow = "overflow";
        long ll = 0;
        if (num > 8)
        {
            return overflow;
        }
        for (int i = begin; i < begin + num; i++)
        {
            ll = ll * 256 + hex[i];
        }
        return String.valueOf(ll);
    }
    /**
     * 獲取日期的年份
     * 
     * @param d 日期
     * @return 年份
     */
    public static int getYear(Date d)
    {
        GregorianCalendar cal = new GregorianCalendar();
        if (d != null)
        {
            cal.setTime(d);
            return cal.get(Calendar.YEAR);
        }
        else
        {
            return 1900;
        }
    }
    /**
     * 獲取日期的月份
     * 
     * @param d 日期
     * @return 月份
     */
    public static int getMonth(Date d)
    {
        GregorianCalendar cal = new GregorianCalendar();
        if (d != null)
        {
            cal.setTime(d);
            return cal.get(Calendar.MONTH) + 1;
        }
        else
        {
            return 1;
        }
    }
    /**
     * 獲取日期的天
     * 
     * @param d 日期
     * @return 天
     */
    public static int getDay(Date d)
    {
        GregorianCalendar cal = new GregorianCalendar();
        if (d != null)
        {
            cal.setTime(d);
            return cal.get(Calendar.DAY_OF_MONTH);
        }
        else
        {
            return 1;
        }
    }
    /**
     * 獲取日期的小時
     * 
     * @param d 日期
     * @return 小時
     */
    public static int getHour(Date d)
    {
        GregorianCalendar cal = new GregorianCalendar();
        if (d != null)
        {
            cal.setTime(d);
            return cal.get(Calendar.HOUR_OF_DAY);
        }
        else
        {
            return 0;
        }
    }
    /**
     * 獲取日期的分
     * 
     * @param d 日期
     * @return 分
     */
    public static int getMinute(Date d)
    {
        GregorianCalendar cal = new GregorianCalendar();
        if (d != null)
        {
            cal.setTime(d);
            return cal.get(Calendar.MINUTE);
        }
        else
        {
            return 0;
        }
    }
    /**
     * 獲取日期的秒
     * 
     * @param d 日期
     * @return 秒
     */
    public static int getSecond(Date d)
    {
        GregorianCalendar cal = new GregorianCalendar();
        if (d != null)
        {
            cal.setTime(d);
            return cal.get(Calendar.SECOND);
        }
        else
        {
            return 0;
        }
    }
    /**
     * 獲取日期的毫秒
     * 
     * @param d 日期
     * @return 毫秒
     */
    public static int getMilliSecond(Date d)
    {
        GregorianCalendar cal = new GregorianCalendar();
        if (d != null)
        {
            cal.setTime(d);
            return cal.get(Calendar.MILLISECOND);
        }
        else
        {
            return 0;
        }
    }
    /**
     * 轉換日期爲MM-dd-yyyy HH:mm:ss格式的字符串
     * 
     * @param d 日期
     * @return 字符串
     */
    public static String toString(Date d)
    {
        if (d == null)
        {
            return null;
        }
        return toString(d, DEFAULT_DATETIME_FORMAT);
    }
    /**
     * 轉換日期爲指定格式的字符串
     * 
     * @param date 日期
     * @param format 指定格式
     * @return 字符串
     */
    public static String toString(Date date, String format)
    {
        if (date == null)
        {
            return "";
        }
        if ((format == null) || (format.length() == 0))
        {
            return "";
        }
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        return formatter.format(date);
    }
    /**
     * 轉換日期爲指定區域內指定格式的字符串
     * 
     * @param date 日期
     * @param format 指定格式
     * @param locale 指定區域
     * @return 字符串
     */
    public static String toString(Date date, String format, Locale locale)
    {
        if (date == null)
        {
            return "";
        }
        if ((format == null) || (format.length() == 0))
        {
            return "";
        }
        if (locale == null)
        {
            return "";
        }
        SimpleDateFormat formatter = new SimpleDateFormat(format, locale);
        return formatter.format(date);
    }
    /**
     * 轉換字符串爲日期
     * 
     * @param s 字符串
     * @return 日期
     */
    public static Date toDate(String s)
    {
        if ((s == null) || (s.length() == 0))
        {
            return null;
        }
        return toDate(s, DEFAULT_DATETIME_FORMAT);
    }
    /**
     * 轉換字符串爲指定格式的日期
     * 
     * @param s 字符串
     * @param format 指定格式
     * @return 日期
     */
    public static Date toDate(String s, String format)
    {
        if ((s == null) || (s.length() == 0))
        {
            return null;
        }
        if ((format == null) || (format.length() == 0))
        {
            return null;
        }
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        ParsePosition pos = new ParsePosition(0);
        Date d = formatter.parse(s, pos);
        return d;
    }
    /**
     * 轉換字符串爲指定區域內指定格式的日期
     * 
     * @param s 字符串
     * @param format 指定格式
     * @param locale 指定區域
     * @return 日期
     */
    public static Date toDate(String s, String format, Locale locale)
    {
        Locale loc;
        if ((s == null) || (s.length() == 0))
        {
            return null;
        }
        if ((format == null) || (format.length() == 0))
        {
            return null;
        }
        if (locale == null)
        {
            loc = Locale.getDefault();
        }
        else
        {
            loc = locale;
        }
        SimpleDateFormat formatter = new SimpleDateFormat(format, loc);
        ParsePosition pos = new ParsePosition(0);
        Date d = formatter.parse(s, pos);
        return d;
    }
    /**
     * 判斷字符串是否爲日期
     * @param s 字符串
     * @return 是否爲日期
     */
    public static boolean isDate(String s)
    {
        Date date = toDate(s);
        if (date == null)
        {
            return false;
        }
        String str = toString(date);
        return str.equalsIgnoreCase(s);
    }
    /**
     * 判斷字符串是否爲指定格式日期
     * @param s 字符串
     * @param format 指定格式
     * @return 是否爲日期
     */
    public static boolean isDate(String s, String format)
    {
        Date date = toDate(s, format);
        if (date == null)
        {
            return false;
        }
        String str = toString(date, format);
        return str.equalsIgnoreCase(s);
    }
    /**
     * 判斷字符串是否爲指定區域內指定格式日期
     * @param s 字符串
     * @param format 指定格式
     * @param locale 指定區域
     * @return 是否爲日期
     */
    public static boolean isDate(String s, String format, Locale locale)
    {
        Date date = toDate(s, format, locale);
        if (date == null)
        {
            return false;
        }
        String str = toString(date, format, locale);
        return str.equalsIgnoreCase(s);
    }
    /**
     * 比較兩日期是否相等
     * @param d0 日期0
     * @param d1 日期1
     * @return 是否相等
     */
    public static boolean compare(Date d0, Date d1)
    {
        if (d0 == null && d1 == null)
        {
            return true;
        }
        if (d0 == null || d1 == null)
        {
            return false;
        }
        else
        {
            return d0.getTime() == d1.getTime();
        }
    }
    /**
     * 將日期轉換爲YYYYMMDDHHMISS類型的方法
     * 
     * @param d Date
     * @return String
     */
    public static String toDate(Date d)
    {
        return toString(d, ZH_SECOND_DATE_FORMAT);
    }
    /**
     * 將日期類型轉換爲微秒級別的字符串,格式爲yyyy:MM:dd HH:mm:ss:SSS
     * 
     * @param d Date
     * @return String
     */
    public static String toDateOfMilliSecond(Date d)
    {
        return toString(d, DEFAULT_PRECISION_MILLTIME_FORMAT);
    }
    /**
     * 返回某日期增減指定月數後的新值
     * 
     * @param oldDate 舊日期,格式:yyyyMMddHHmmss
     * @param valve 增減月數
     * @return 新日期,格式:yyyyMMddHHmmss
     */
    public static String getDateByAddMonth(String oldDate, int valve)
    {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(toDate(oldDate, ZH_SECOND_DATE_FORMAT));
        calendar.add(Calendar.MONTH, valve);
        return DateUtil.toDate(calendar.getTime());
    }
    /**
     * 計算增加年份後新的日期的值
     * 
     * @param oldDate 之前的日期,精確到秒級,字符串類型,如20060901235959
     * @param valve 閥值
     * @return 新日期
     */
    public static String getDateByAddYear(String oldDate, int valve)
    {
        int year = Integer.parseInt(oldDate.substring(0, 4));
        String newDate = null;
        newDate = String.valueOf(year + valve) + oldDate.substring(4, oldDate.length());
        return newDate;
    }
    /**
     * 計算增加日期後新的日期的值。
     * 
     * @param oldDate 之前的日期,精確到秒級,字符串類型,如20060901235959
     * @param valve 閥值
     * @return 新日期
     */
    public static String getDateByAddDay(String oldDate, int valve)
    {
        Date a = toDate(oldDate, ZH_SECOND_DATE_FORMAT);
        long b = a.getTime();
        long c = b + valve * 24 * 60 * 60 * 1000;
        Date d = new Date(c);
        return toDate(d);
    }
    /**
     * 計算增加小時後新的日期的值。
     * 
     * @param oldDate 之前的日期,精確到秒級,字符串類型,如20060901235959
     * @param valve 閥值
     * @return 新日期
     */
    public static String getDateByAddHour(String oldDate, int valve)
    {
        Date a = toDate(oldDate, ZH_SECOND_DATE_FORMAT);
        long b = a.getTime();
        long c = b + valve * 60 * 60 * 1000;
        Date d = new Date(c);
        return toDate(d);
    }
    /**
     * 計算增加分鐘後新的日期的值。
     * 
     * @param oldDate 之前的日期,精確到秒級,字符串類型,如20060901235959
     * @param valve 閥值
     * @return 新日期
     */
    public static String getDateByAddMinute(String oldDate, int valve)
    {
        Date a = toDate(oldDate, ZH_SECOND_DATE_FORMAT);
        long b = a.getTime();
        long c = b + valve * 60 * 1000;
        Date d = new Date(c);
        return toDate(d);
    }
    /**
     * 計算增加秒鐘後新的日期的值。
     * 
     * @param oldDate 之前的日期,精確到秒級,字符串類型,如20060901235959
     * @param valve 閥值
     * @return 新日期
     */
    public static String getDateByAddSecond(String oldDate, int valve)
    {
        Date a = toDate(oldDate, ZH_SECOND_DATE_FORMAT);
        long b = a.getTime();
        long c = b + valve * 1000;
        Date d = new Date(c);
        return toDate(d);
    }
    /**
     * 取得當前時間 falg=0 格式爲:yyyy.MM.dd HH:mm:ss falg=1 格式爲:mm
     * 
     * @param flag 標誌
     * @return 當前時間
     */
    public static String getTime(int flag)
    {
        java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
        String operTime = formatter.format(new java.util.Date());
        String sMoth = operTime.substring(5, 7);
        if (flag == 0)
        {
            return operTime;
        }
        else
        {
            return sMoth;
        }
    }
    /**
     * 判斷是否是閏年
     * @param year 年份
     * @return 是否是閏年
     */
    public static boolean isLeapYear(int year)
    {
        if (year < 0)
        {
            return false;
        }
        if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    /**
     * 把傳進來的 日期+時間 格式填充。把時間的 時、分、秒的數字填充爲2位。不足2位的前面補0
     * 
     * @param datetime 日期
     * @return 補充後的日期
     */
    public static String fillDateTime(String datetime)
    {
        if (datetime == null || datetime.trim().length() == 0)
        {
            return "";
        }
        String[] ary = datetime.split(" ");
        if (ary == null || ary.length != 2)
        { //這裏對日期時間不做合法性檢查。設定該日期時間都是合法的。
          //簡單的檢查下,如果格式不合法,直接返回空字符串
            return "";
        }
        //這裏暫時對日期格式不做轉換,只對時間格式做轉換 
        String time = fillTime(ary[1]);
        if (time.trim().length() == 0)
        {//如果時間格式轉換錯誤,則返回空字符串
            return "";
        }
        String date = fillDate(ary[0].replaceAll("\\.", "-"));
        if (date.trim().length() == 0)
        {
            return "";
        }
        return date + " " + time;
    }
    /**
     * 填充日期
     * @param date 日期
     * @return 日期
     */
    public static String fillDate(String date)
    {
        if (date == null || date.length() == 0)
        {
            return "";
        }//2009-9-9
        String[] ary = date.split("-");
        if (ary.length != 3 || ary[1] == null || ary[1].trim().length() == 0 || ary[2] == null
                || ary[2].trim().length() == 0 || (ary[1].trim().length() != 1 && ary[1].trim().length() != 2)
                || (ary[2].trim().length() != 1 && ary[2].trim().length() != 2))
        {
            return "";
        }
        if (ary[1].length() == 1)
        {
            ary[1] = "0" + ary[1];
        }
        if (ary[2].length() == 1)
        {
            ary[2] = "0" + ary[2];
        }
        return ary[0] + "-" + ary[1] + "-" + ary[2];
    }
    /**
     * 填充時間格式. 把時間的 時、分、秒的數字填充爲2位。不足2位的前面補0 轉換後的格式爲: HH:mm:ss
     * 
     * @param time 日期
     * @return 日期
     */
    public static String fillTime(String time)
    {
        //這裏對時間的合法性不做檢查
        if (time == null)
        {
            return "";
        }
        time = time.trim();
        if (time.equals(""))
        {
            return "";
        }
        String[] timesplit = time.split(":", 3);
        if (timesplit.length != 3)
        {
            return "";
        }
        if (timesplit[0] == null || timesplit[1] == null || timesplit[2] == null)
        {
            return "";
        }
        String shour = timesplit[0].trim();
        String sminute = timesplit[1].trim();
        String ssecond = timesplit[2].trim();
        if (shour.equals("") || sminute.equals("") || ssecond.equals(""))
        {
            return "";
        }
        if (shour.length() == 1)
        {
            shour = "0" + shour;
        }
        if (sminute.length() == 1)
        {
            sminute = "0" + sminute;
        }
        if (ssecond.length() == 1)
        {
            ssecond = "0" + ssecond;
        }
        return shour + ":" + sminute + ":" + ssecond;
    }
    /**
     * 檢測輸入字符串是否是時間格式 HH:mm:dd
     * 
     * @param s 日期
     * @return 是否是時間格式
     */
    public static boolean checkTimeFormat(String s)
    {
        if (s == null)
        {
            return false;
        }
        s = s.trim();
        if (s.equals(""))
        {
            return false;
        }
        String[] timesplit = s.split(":", 3);
        if (timesplit.length != 3)
        {
            return false;
        }
        if (timesplit[0] == null || timesplit[1] == null || timesplit[2] == null)
        {
            return false;
        }
        String shour = timesplit[0].trim();
        String sminute = timesplit[1].trim();
        String ssecond = timesplit[2].trim();
        if (shour.equals("") || sminute.equals("") || ssecond.equals(""))
        {
            return false;
        }
        try
        {
            int ihour = Integer.parseInt(shour);
            if (shour.trim().length() != 2 && shour.trim().length() != 1)
            {
                return false;
            }
            if (ihour > 23 || ihour < 0)
            {
                return false;
            }
            if (sminute.trim().length() != 2 && sminute.trim().length() != 1)
            {
                return false;
            }
            int iminute = Integer.parseInt(sminute);
            if (iminute < 0 || iminute > 59)
            {
                return false;
            }
            if (ssecond.trim().length() != 2 && ssecond.trim().length() != 1)
            {
                return false;
            }
            int isecond = Integer.parseInt(ssecond);
            if (isecond < 0 || isecond > 59)
            {
                return false;
            }
        }
        catch (Exception e)
        {
            return false;
        }
        return true;
    }
    /**
     * 檢測輸入字符串是否是 日期+時間 格式,包括閏年檢測
     * @param s 日期
     * @return 是否是日期+時間 格式
     */
    public boolean checkDateTimeFormat(String s)
    {
        if (s == null)
        {
            return false;
        }
        s = s.trim();
        if (s.equals(""))
        {
            return false;
        }
        String[] dtparts = s.split(" ", 2);
        if (dtparts.length != 2)
        {
            return false;
        }
        String dateparts = dtparts[0];
        String timeparts = dtparts[1];
        return checkDateFormat(dateparts) && checkTimeFormat(timeparts);
    }
    /**
     * 檢測輸入字符串是否是日期格式yyyy-MM-dd,包括閏年檢測
     * @param s 日期
     * @return 是否是日期格式yyyy-MM-dd
     */
    public static boolean checkDateFormat(String s)
    {
        if (s == null)
        {
            return false;
        }
        s = s.trim();
        if (s.equals(""))
        {
            return false;
        }
        String[] dts = s.split("-");
        if (dts.length != 3)
        {
            return false;
        }
        if (dts[0].length() != 4)
        {
            return false;
        }
        if ((dts[1].length() != 1 && dts[1].length() != 2))
        {
            return false;
        }
        if (dts[2].length() != 1 && dts[2].length() != 2)
        {
            return false;
        }
        int year = 0;
        int month = 0;
        int day = 0;
        int days = 0;
        try
        {
            year = Integer.valueOf(dts[0]);
            if (year > 10000 || year < 1)
            {
                return false;
            }
        }
        catch (Exception e)
        {
            return false;
        }
        try
        {
            month = Integer.valueOf(dts[1]);
            if (month < 1 || month > 12)
            {
                return false;
            }
        }
        catch (Exception e)
        {
            return false;
        }
        try
        {
            day = Integer.valueOf(dts[2]);
            switch (month)
            {
                case 1:
                case 3:
                case 5:
                case 7:
                case 8:
                case 10:
                case 12:
                    days = 31;
                    break;
                case 4:
                case 6:
                case 9:
                case 11:
                    days = 30;
                    break;
                case 2:
                    if (isLeapYear(year))
                    {
                        days = 29;
                    }
                    else
                    {
                        days = 28;
                    }
                default:
            }
            if (day > days || day < 1)
            {
                return false;
            }
        }
        catch (Exception e)
        {
            return false;
        }
        return true;
    }
    /**
     * 把字符串轉換成 日期
     * @param strdate 字符串日期
     * @return 日期
     */
    public Date stringParsetoDate(String strdate)
    {
        if (strdate == null || strdate.trim().equals(""))
        {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try
        {
            return sdf.parse(strdate);
        }
        catch (Exception e)
        {
            return null;
        }
    }
    /**
     * 把字符串轉換成 日期時間
     * @param str 字符串日期
     * @return 日期
     */
    public Date strToDateTime(String str)
    {
        if (str == null || str.trim().equals(""))
        {
            return null;
        }
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try
        {
            return sdf.parse(str);
        }
        catch (Exception e)
        {
            return null;
        }
    }
    /**
     * 從字符串中得到月份
     * @param datestr 字符串日期
     * @return 月份
     */
    public int getMonthfromStr(String datestr)
    {
        int month = 0;
        if (datestr == null || datestr.trim().equals(""))
        {
            return month;
        }
        String[] splitedate = datestr.split("-");
        try
        {
            month = Integer.parseInt(splitedate[1].trim());
            if (month < 1 || month > 12)
            {
                return 0;
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return 0;
        }
        return month;
    }
    /**
     * 把給定日期減去N個月,返回一個Date
     * @param date 給定日期
     * @param nMonth 月數
     * @return Date
     * @throws Exception 拋出的異常
     */
    public Date minusMonth(Calendar date, int nMonth) throws Exception
    {
        date.add(Calendar.MONTH, -nMonth);
        SimpleDateFormat spdf = new SimpleDateFormat("yyyy-MM-dd");
        return spdf.parse(spdf.format(date.getTime()));
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章