史上最全的時間工具類

package cpcn.payment.feebatch.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import cpcn.payment.api.constant.fee.FeeErrorMsgConstants;
import cpcn.payment.api.enumeration.jifei.CycleTypeEnum;
import cpcn.payment.tool.system.CodeException;



public class CalenderUtils {

    private final static String DATE_FORMAT = "yyyyMM";

    private final static String DATE_FORMAT2 = "yyyyMMdd";

    private final static String DATE_FORMAT3 = "yyyyMMddHHmmssSSS";

    /**
     * 獲得當前月
     * 
     * @return
     */
    public static int getCurrentMonth() {
        Calendar calendar = Calendar.getInstance();
        int month = calendar.get(Calendar.MONTH) + 1;
        return month;
    }

    /**
     * 獲得當前時間:yyyyMM
     * 
     * @return
     */
    public static String getCurrentYearAndMonth() {
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
        return sdf.format(new Date());
    }

    /**
     * 獲得當前時間:yyyyMMddhhmmssSSS
     * 
     * @return
     */
    public static String getCurrentTime() {
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT3);
        return sdf.format(new Date());
    }

    /**
     * 獲得本日的前幾個月時間
     * 
     * @return
     */
    public static String getDateBeforeMonth(int number) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, -number);
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
        return sdf.format(cal.getTime());
    }

    /**
     * 獲得本日的前幾個月時間
     * 
     * @return
     */
    public static String getDateBeforeMonth2(int monthNumber) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, -monthNumber);
        cal.set(Calendar.DAY_OF_MONTH, 1);

        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT2);
        String time = sdf.format(cal.getTime());
        return time.concat("000000000");
    }

    /**
     * 獲得本日的前幾個月時間的固定天數後
     * 
     * @return
     */
    public static String getDateBeforeMonthAfterDays(int monthNumber, int dayNumber) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, -monthNumber);
        cal.set(Calendar.DATE, dayNumber + 1);

        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT2);
        String time = sdf.format(cal.getTime());
        return time.concat("000000000");
    }

    /**
     * 獲得週期內的時間範圍
     * 
     * @return
     */
    public static Object[] getMonthRange(int cycleType) {
        List<String> dates = new ArrayList<String>();

        if (cycleType == CycleTypeEnum.MONTH.getValue()) {
            dates.add(getDateBeforeMonth2(1));
            dates.add(getDateBeforeMonth2(0));
        } else if (cycleType == CycleTypeEnum.QUARTER.getValue()) {
            dates.add(getDateBeforeMonth2(3));
            dates.add(getDateBeforeMonth2(0));
        } else if (cycleType == CycleTypeEnum.YEAR.getValue()) {
            dates.add(getDateBeforeMonth2(12));
            dates.add(getDateBeforeMonth2(0));
        }
        return dates.toArray();
    }

    /**
     * 獲得週期內的時間範圍(到固定天數後)
     * 
     * @return
     */
    public static Object[] getMonthRangeOfFixedDays(int cycleType, int dayNumber) {
        List<String> dates = new ArrayList<String>();

        if (cycleType == CycleTypeEnum.MONTH.getValue()) {
            dates.add(getDateBeforeMonth2(1));
            dates.add(getDateBeforeMonthAfterDays(1, dayNumber));
        } else if (cycleType == CycleTypeEnum.QUARTER.getValue()) {
            dates.add(getDateBeforeMonth2(3));
            dates.add(getDateBeforeMonthAfterDays(3, dayNumber));
        } else if (cycleType == CycleTypeEnum.YEAR.getValue()) {
            dates.add(getDateBeforeMonth2(12));
            dates.add(getDateBeforeMonthAfterDays(12, dayNumber));
        }
        return dates.toArray();
    }

    /**
     * 獲得當前月的天數
     * 
     * @return
     */
    public static int getDaysOfLastMonth() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, -1);
        return cal.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    /**
     * 獲得前n個月的天數
     * 
     * @return
     */
    public static int getDaysBeforeMonth(int number) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, -number);
        return cal.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    /**
     * 
     * @param number
     * @return 前n個月的總天數
     */
    public static int getTotalDaysBeforeMonth(int number) {
        int totalDays = 0;
        for (int i = number; i > 0; i--) {
            totalDays += getDaysBeforeMonth(i);
        }
        return totalDays;
    }

    /**
     * 
     * @param startTime
     *            endTime
     * @return 獲得任意時間段內的總天數
     */
    public static int getDayCount(String startTime, String endTime) throws CodeException {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT2);
            int spaceDay = (int) ((sdf.parse(endTime).getTime() - sdf.parse(startTime).getTime()) / (1000 * 60 * 60 * 24));
            return spaceDay;
        } catch (ParseException e) {
            throw new CodeException(FeeErrorMsgConstants.ERR_8001_CODE, FeeErrorMsgConstants.ERR_8001_MSG + "getDayCount()");
        }
    }

    /**
     * 
     * @param startTime
     *            days
     * @return 獲得任意天數後的日期
     */
    public static String getAfterDaysTime(String startTime, int days) throws CodeException {
        try {
            // 日期格式
            SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT2);
            // 指定日期
            Date date = dateFormat.parse(startTime);
            // 指定日期加上20天
            Date newDate = addDate(date, days);
            // 輸出格式化後的日期
            return dateFormat.format(newDate).concat("000000000");
        } catch (ParseException e) {
            throw new CodeException(FeeErrorMsgConstants.ERR_8001_CODE, FeeErrorMsgConstants.ERR_8001_MSG + "getAfterDaysTime()");
        }
    }

    /**
     * 
     * @param date
     *            day
     * @return 獲得任意天數後的日期
     */
    public static Date addDate(Date date, long day) throws ParseException {
        // 獲得指定日期的毫秒數
        long time = date.getTime();
        // 要加上的天數轉換成毫秒數
        // SUPPRESS CHECKSTYLE
        day = day * 24 * 60 * 60 * 1000;
        // 相加獲得新的毫秒數
        time += day;
        // 將毫秒數轉換成日期
        return new Date(time);
    }
}


package cpcn.payment.tool.lang;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;


public class TimeUtil {
    // 模板
    public static final String PATTERN_DATE8 = "yyyyMMdd";

    public static final String PATTERN_DATE8_2 = "yyyy-MM-dd";

    public static final String PATTERN_TIME6 = "HHmmss";

    public static final String PATTERN_TIME14 = "yyyyMMddHHmmss";

    public static final String PATTERN_TIME14_2 = "yyyy-MM-dd HH:mm:ss";

    public static final String PATTERN_TIME17 = "yyyyMMddHHmmssSSS";

    public static String getFormattedDate(Date date) {
        if (date == null) {
            return null;
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            return sdf.format(date);
        }
    }

    public static String getFormattedDate(Date date, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(date);
    }

    /**
     * <p>
     * Description 獲取當前日期的上個月
     * </p>
     * 
     * @author dairongsheng
     * @date 2017年7月19日 下午6:12:17
     * @return
     */
    public static String getFormattedLastMonth() {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH, -1);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        String time = format.format(c.getTime());
        return time;
    }

    public static String getFormattedTime(Date date) {
        if (date == null) {
            return "";
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return sdf.format(date);
        }
    }

    /**
     * 格式:yyyyMMddHHmmss
     * 
     * @param date
     * @return
     */
    public static String getFormattedTime2(Date date) {
        if (date == null) {
            return "";
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            return sdf.format(date);
        }
    }

    /**
     * <p>
     * 返回系統時間組成的字符串。例如:20050828143158
     * <p>
     * 
     * @return String
     */
    public static String getTimeStamp() {
        Calendar calendar = Calendar.getInstance();
        Date date = calendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        return sdf.format(date);
    }

    /**
     * <p>
     * 返回系統時間組成的字符串。例如:20050828
     * <p>
     * 
     * @return String
     */
    public static String getDateStamp() {
        Calendar calendar = Calendar.getInstance();
        Date date = calendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        return sdf.format(date);
    }

    /**
     * <p>
     * 返回多少天前系統時間組成的字符串。例如:20050828
     * <p>
     * 
     * @return String
     */
    public static String getDateStamp(int time) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 0 - time);
        Date date = calendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        return sdf.format(date);
    }

    /**
     * <p>
     * 返回系統時間組成的字符串。例如:2005-08-28
     * <p>
     * 
     * @return String
     */
    public static String getCurrentDate() {
        Calendar calendar = Calendar.getInstance();
        Date date = calendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(date);
    }

    /**
     * <p>
     * 返回系統時間組成的字符串。例如:2005-08-28 14:20:36
     * <p>
     * 
     * @return String
     */
    public static String getCurrentTime() {
        Calendar calendar = Calendar.getInstance();
        Date date = calendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }

    /**
     * <p>
     * 返回系統時間組成的字符串。例如:200508
     * <p>
     * 
     * @return String
     */
    public static String getMonthStamp() {
        Calendar calendar = Calendar.getInstance();
        Date date = calendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        return sdf.format(date);
    }

    /**
     * 返回某年某月的天數
     * 
     * @param year
     *            int
     * @param month
     *            int
     * @return int
     */
    public static int getDays(int year, int month) {
        int days = 30;
        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 ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
                    days = 29;
                } else {
                    days = 28;
                }
                break;
            default:
        }
        return days;
    }

    /**
     * Returns true if the specified date string represents a valid date in the
     * specified format.
     * 
     * @param dateString
     *            a String representing a date/time.
     * @param dateFormatPattern
     *            a String specifying the format to be used when parsing the
     *            dateString. The pattern is expressed with the pattern letters
     *            defined for the java.text.SimpleDateFormat class.
     * @return boolean - return true if valid, false otherwise.
     */
    public static boolean isValidDate(String dateString, String dateFormatPattern) {

        // 長度校驗追加 竇彬 2015/3/17 begin
        if (StringUtil.isEmpty(dateString) || StringUtil.isEmpty(dateFormatPattern)) {
            return false;
        }

        if (dateString.length() != dateFormatPattern.length()) {
            return false;
        }
        // 長度校驗追加 竇彬 2015/3/17 end

        Date validDate = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(dateFormatPattern);
            sdf.setLenient(false);
            validDate = sdf.parse(dateString);
        } catch (ParseException e) {
            return validDate != null;
        }

        return validDate != null;
    }

    public static Date string2Date(String date, String format) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        try {
            return simpleDateFormat.parse(date);
        } catch (ParseException e) {
            throw e;
        }

    }

    public static String date2String(Date date, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(date);
    }

    /**
     * 
     * @return 當前時間
     */
    public static Date getNowTime() {
        return Calendar.getInstance().getTime();
    }

    /**
     * 
     * @return 當前時間
     */
    public static long getNowTimeInMillis() {
        return Calendar.getInstance().getTimeInMillis();
    }

    /**
     * <p>
     * 返回系統時間組成的字符串。例如:20050828143158333
     * <p>
     * 
     * @return String
     */
    public static String getTimeMillisecondStamp() {
        Calendar calendar = Calendar.getInstance();
        Date date = calendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return sdf.format(date);
    }

    /**
     * <p>
     * 返回多少天后系統時間組成的字符串。例如:20050828143158333
     * <p>
     * 
     * @return String
     */
    public static String getTimeMillisecondStamp(int days) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, days);
        Date date = calendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return sdf.format(date);
    }

    public static String transformTime(String date, String sourceFormat, String destFormat) throws Exception {
        SimpleDateFormat sdfSource = new SimpleDateFormat(sourceFormat);
        Date dateSource = sdfSource.parse(date);
        SimpleDateFormat sdfDest = new SimpleDateFormat(destFormat);
        return sdfDest.format(dateSource);
    }

    public static Timestamp stringToTimestamp(String datetime) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        Timestamp ts = new Timestamp(formatter.parse(datetime).getTime());
        return ts;
    }

    public static String addDays(int days) {
        String fromTime = "";
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        calendar.add(Calendar.DAY_OF_MONTH, days);

        Date date = calendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        fromTime = sdf.format(date);
        return fromTime;
    }

    public static Date addDays(java.util.Date date, int days) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, days);
        return calendar.getTime();
    }

    public static String addDays(String dateStr, int days) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        sdf.setLenient(false);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(sdf.parse(dateStr));
        calendar.add(Calendar.DATE, days);
        return sdf.format(calendar.getTime());
    }

    /**
     * 小時變化
     * 
     * @param timeStr
     * @param hours
     * @return
     * @throws ParseException
     */
    public static String addHours(String timeStr, int hours) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        sdf.setLenient(false);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(sdf.parse(timeStr));
        calendar.add(Calendar.HOUR, hours);
        return sdf.format(calendar.getTime());
    }

    /**
     * 判斷time1與time2的大小;若是time1大於time2,則返回true;不然返回false;
     * 
     * @param time1
     * @param time2
     * @param pattern
     *            time1與time2均符合pattern模式
     * @return
     * @throws ParseException
     */
    public static boolean isAfter(String time1, String time2, String pattern) throws ParseException {
        Date date1 = TimeUtil.string2Date(time1, pattern);
        Date date2 = TimeUtil.string2Date(time2, pattern);
        long tim1 = date1.getTime();
        long tim2 = date2.getTime();

        return tim1 > tim2;
    }

    /**
     * 計算當前時間到下offset個整點的時間
     * 
     * @param offset
     *            小時個數,好比計算當前時間到下一個整點的時間,傳值爲1;到第二個整點,則傳值爲2;依次類推
     * @return
     */
    public static long nextHourDelay(int offset) {
        Calendar calendar = Calendar.getInstance();
        long currTime = calendar.getTimeInMillis();

        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        calendar.set(Calendar.HOUR_OF_DAY, hour + offset);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        long nextHourTime = calendar.getTimeInMillis();

        return nextHourTime - currTime;
    }

    /**
     * <p>
     * Description:獲取指定月份的最後一天:舉例 201707 獲取到 20170731
     * </p>
     * 
     * @author dairongsheng
     * @date 2017年7月5日 下午2:04:39
     * @param month
     * @return
     */
    public static String getLastDayOfMonth(String month) {        
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, Integer.valueOf(month.substring(0, 4)));
        cal.set(Calendar.MONTH, Integer.valueOf(month.substring(4)) - 1);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.add(Calendar.MONTH, 1);
        cal.add(Calendar.DAY_OF_MONTH,-1);
        return new SimpleDateFormat("yyyyMMdd").format(cal.getTime());
    }
           
    /**
     * <p>
     * Description 獲取指定日期當月第一天。好比20170718,當月第一天是20170701
     * </p>
     * 
     * @author dairongsheng
     * @date 2017年7月7日 下午4:28:46
     * @param date
     * @return
     */
    public static String getFirstDayOfMonth(String date) {
        String s = date.substring(0, 6) + "01";
        return s;
    }

    /**
     * <p>
     * Description 獲取指定日期的前一天,好比20170701前一天是20170630
     * </p>
     * 
     * @author dairongsheng
     * @date 2017年7月7日 上午9:36:16
     * @param date
     * @return
     */
    public static String getBeforeDay(String date) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, Integer.valueOf(date.substring(0, 4)));
        cal.set(Calendar.MONTH, Integer.valueOf(date.substring(4, 6)) - 1);
        cal.set(Calendar.DAY_OF_MONTH, Integer.valueOf(date.substring(6)));
        cal.add(Calendar.DAY_OF_MONTH, -1);
        return new SimpleDateFormat("yyyyMMdd").format(cal.getTime());
    }

    /**
     * <p>
     * Description:獲取指定年月有多少天
     * </p>
     * 
     * @author dairongsheng
     * @date 2017年7月5日 下午2:50:23
     * @param month
     * @return
     */
    public static int getDayNumberByMonth(String month) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, Integer.valueOf(month.substring(0, 4)));
        cal.set(Calendar.MONTH, Integer.valueOf(month.substring(4)) - 1);
        int dayNumber = cal.getActualMaximum(Calendar.DATE);
        return dayNumber;
    }

    /**
     * <p>
     * Description 舉例:date=20170706 返回值是20170707000000000
     * 
     * @author dairongsheng
     * @date 2017年7月21日 上午9:56:46
     * @param date
     */
    public static String getNextDayTime(String date) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, Integer.valueOf(date.substring(0, 4)));
        cal.set(Calendar.MONTH, Integer.valueOf(date.substring(4, 6)) - 1);
        cal.set(Calendar.DAY_OF_MONTH, Integer.valueOf(date.substring(6)));
        cal.add(Calendar.DAY_OF_MONTH, 1);
        String s = new SimpleDateFormat("yyyyMMdd").format(cal.getTime());
        return s + "000000000";
    }

}