【分享】java時間操作工具

 項目中對時間的操作是很頻繁的,我分享一下我工作中積累下來的時間操作工具。

package com.lion.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
/**
 * 時間操作工具
 * @author liyongyao
 *
 */
public class TimeUtil {
    private static final String DATETIME = "yyyy-MM-dd HH:mm:ss";
    private static final String DATE = "yyyy-MM-dd";
    private static final String TIME = "HH:mm:dd";
    private static final String YEAR = "yyyy";
    private static final String MONTH = "MM";
    private static final String DAY = "dd";
    private static final String HOUR = "HH";
    private static final String MINUTE = "mm";
    private static final String SEC = "ss";
    private static final String DATETIMECHINESE = "yyyy年MM月dd日 HH時mm分ss秒";
    private static final String DATECHINESE = "yyyy年MM月dd日";
    private static final String SIMPLEDATECHINESE = "MM月dd日";
    /**
     * 判斷一個字符串日期是否過期
     *
     * @param dateTime
     * @return (int) 過期返回1,不過期返回0
     * @throws ParseException
     */
    public static int isOutOfDate(String dateTime) throws ParseException {
        long nowTimeLong = new Date().getTime();
        long ckTimeLong = new SimpleDateFormat(DATETIME).parse(dateTime)
                .getTime();
        if (nowTimeLong - ckTimeLong > 0) {// 過期
            return 1;
        }
        return 0;
    }
    /**
     * 判斷是否在一個起止日期內<br/>
     * 例如:2012-04-05 00:00:00~2012-04-15 00:00:00
     *
     * @param start_time
     * @param over_time
     * @return (int)&nbsp;在這個時間段內返回1,不在返回0
     * @throws ParseException
     */
    public static int isOutOfDate(String start_time, String over_time)
            throws ParseException {
        long nowTimeLong = new Date().getTime();
        long ckStartTimeLong = new SimpleDateFormat(DATETIME).parse(start_time)
                .getTime();
        long ckOverTimeLong = new SimpleDateFormat(DATETIME).parse(over_time)
                .getTime();
        if (nowTimeLong > ckStartTimeLong && nowTimeLong < ckOverTimeLong) {
            return 1;
        }
        return 0;
    }
    /**
     * 判斷一個自定義日期是否在一個起止日期內<br/>
     * 例如:判斷2012-01-05 00:00:00是否在2012-04-05 00:00:00~2012-04-15 00:00:00
     *
     * @param start_time
     * @param over_time
     * @return (int)&nbsp;在這個時間段內返回1,不在返回0
     * @throws ParseException
     */
    public static int isOutOfDate(String time, String start_time,
            String over_time) throws ParseException {
        long timeLong = new SimpleDateFormat(DATETIME).parse(time).getTime();
        long ckStartTimeLong = new SimpleDateFormat(DATETIME).parse(start_time)
                .getTime();
        long ckOverTimeLong = new SimpleDateFormat(DATETIME).parse(over_time)
                .getTime();
        if (timeLong > ckStartTimeLong && timeLong < ckOverTimeLong) {
            return 1;
        }
        return 0;
    }
    /**
     * 判斷是否在一個時間段內<br/>
     * 例如:8:00~10:00
     *
     * @param time_limit_start
     * @param time_limit_over
     * @return (int) 1在這個時間段內,0不在這個時間段內
     * @throws ParseException
     */
    public static int isInTime(String time_limit_start, String time_limit_over)
            throws ParseException {
        // 獲取當前日期
        String nowDate = new SimpleDateFormat(DATE).format(new Date());
        return isOutOfDate(nowDate + " " + time_limit_start, nowDate + " "
                + time_limit_over);
    }
    /**
     * 判斷一個自定義時間是否在一個時間段內<br/>
     * 例如:判斷02:00是否在08:00~10:00時間段內
     *
     * @param time_limit_start
     * @param time_limit_over
     * @return (int) 1在這個時間段內,0不在這個時間段內
     * @throws ParseException
     */
    public static int isInTime(String time, String time_limit_start,
            String time_limit_over) throws ParseException {
        String nowDate = new SimpleDateFormat(DATE).format(new Date());
        return isOutOfDate(nowDate + " " + time, nowDate + " "
                + time_limit_start, nowDate + " " + time_limit_over);
    }
    /**
     * 取得自定義月份後的日期,如13個月以後的時間
     *
     * @param monthNum
     *            往後幾個月
     * @return 時間字符串
     */
    public static String crateTimeFromNowTimeByMonth(int monthNum) {
        Calendar calendar = new GregorianCalendar(Integer.parseInt(getYear()),
                Integer.parseInt(getMonth()) - 1, Integer.parseInt(getDay()),
                Integer.parseInt(getHour()), Integer.parseInt(getMinute()),
                Integer.parseInt(getSec()));
        calendar.add(Calendar.MONTH, monthNum);
        return new SimpleDateFormat(DATETIME).format(calendar.getTime());
    }
    /**
     * 取得自定義天數後的日期,如13天以後的時間
     *
     * @param dayNum
     *            往後幾天
     * @return 時間字符串(DateTime)
     */
    public static String crateTimeFromNowTimeByDay(int dayNum) {
        Calendar calendar = new GregorianCalendar(Integer.parseInt(getYear()),
                Integer.parseInt(getMonth()) - 1, Integer.parseInt(getDay()),
                Integer.parseInt(getHour()), Integer.parseInt(getMinute()),
                Integer.parseInt(getSec()));
        calendar.add(Calendar.DATE, dayNum);
        return new SimpleDateFormat(DATETIME).format(calendar.getTime());
    }
                             
    /**
     * 取得自定義天數後的日期,如13天以後的時間
     *
     * @param dayNum
     *            往後幾天
     * @return 時間字符串(Date)
     */
    public static String crateTimeFromNowDayByDay(int dayNum) {
        Calendar calendar = new GregorianCalendar(Integer.parseInt(getYear()),
                Integer.parseInt(getMonth()) - 1, Integer.parseInt(getDay()),
                Integer.parseInt(getHour()), Integer.parseInt(getMinute()),
                Integer.parseInt(getSec()));
        calendar.add(Calendar.DATE, dayNum);
        return new SimpleDateFormat(DATE).format(calendar.getTime());
    }
    /**
     * 取得自定義時間後再過幾分鐘的時間,如12:05以後5分鐘的時間
     *
     * @param dayNum
     *            往後幾天
     * @return 時間字符串(Date)
     */
    public static String crateTimeFromNowDayByTime(int timeNum) {
        Calendar calendar = new GregorianCalendar(Integer.parseInt(getYear()),
                Integer.parseInt(getMonth()) - 1, Integer.parseInt(getDay()),
                Integer.parseInt(getHour()), Integer.parseInt(getMinute()),
                Integer.parseInt(getSec()));
        calendar.add(Calendar.MINUTE, timeNum);
        return new SimpleDateFormat(DATETIME).format(calendar.getTime());
    }
    /**
     * 計算兩個時間間隔(精確到分鐘)
     *
     * @param startDay
     *            開始日(整型):0表示當日,1表示明日
     * @param startTime
     *            開始時間(24h):00:00
     * @param endDay
     *            結束日(整型):0表示當日,1表示明日,限制:大於等於 startDay
     * @param endTime
     *            結束時間(24h):23:50
     * @return 格式化的日期格式:DD天HH小時mm分
     */
    public static String calculateIntervalTime(int startDay, String startTime,
            int endDay, String endTime) {
        int day = endDay - startDay;
        int hour = 0;
        int mm = 0;
        if (day < 0) {
            return null;
        } else {
            int sh = Integer.valueOf(startTime.split(":")[0]);
            int eh = Integer.valueOf(endTime.split(":")[0]);
            int sm = Integer.valueOf(startTime.split(":")[1]);
            int em = Integer.valueOf(endTime.split(":")[1]);
            hour = eh - sh;
            if (hour > 0) {
                mm = em - sm;
                if (mm < 0) {
                    hour--;
                    mm = 60 + mm;
                }
            } else {
                day = day - 1;
                hour = 24 + hour;
                mm = em - sm;
                if (mm < 0) {
                    hour--;
                    mm = 60 + mm;
                }
            }
        }
        if (hour == 24) {
            day++;
            hour = 0;
        }
        if (day != 0) {
            return day + "天" + hour + "小時" + mm + "分";
        } else {
            return hour + "小時" + mm + "分";
        }
    }
    /**
     * 計算兩個時間差
     *
     * @param startTime
     * @param endTime
     * @return long
     * @throws ParseException
     */
    public static long calculateIntervalTime(String startTime, String endTime)
            throws ParseException {
        return parseDateTime(endTime).getTime()
                - parseDateTime(startTime).getTime();
    }
    // 字符串轉換成時間
    public static Date parseDateTime(String datetime) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat(DATETIME);
        return sdf.parse(datetime);
    }
    // 獲取當前詳細日期時間
    public static String getDateTime() {
        return new SimpleDateFormat(DATETIME).format(new Date());
    }
    // 轉換爲中文時間
    public static String getChineseDateTime() {
        return new SimpleDateFormat(DATETIMECHINESE).format(new Date());
    }
    // 轉換爲中文時間
    public static String getChineseDate() {
        return new SimpleDateFormat(DATECHINESE).format(new Date());
    }
    // 轉換爲中文時間
    public static String getSimpleChineseDate() {
        return new SimpleDateFormat(SIMPLEDATECHINESE).format(new Date());
    }
    // 轉換爲中文時間 如果num爲-1表示前一天 1爲後一天 0爲當天
    public static String getSimpleChineseDate(int num) {
        Date d = new Date();
        try {
            d = parseDateTime(crateTimeFromNowTimeByDay(num));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return new SimpleDateFormat(SIMPLEDATECHINESE).format(d);
    }
    // 獲取當前時間
    public static String getTime() {
        return new SimpleDateFormat(TIME).format(new Date());
    }
    // 獲取當前年
    public static String getYear() {
        return new SimpleDateFormat(YEAR).format(new Date());
    }
    // 獲取當前月
    public static String getMonth() {
        return new SimpleDateFormat(MONTH).format(new Date());
    }
    // 獲取當前日
    public static String getDay() {
        return new SimpleDateFormat(DAY).format(new Date());
    }
    // 獲取當前時
    public static String getHour() {
        return new SimpleDateFormat(HOUR).format(new Date());
    }
    // 獲取當前分
    public static String getMinute() {
        return new SimpleDateFormat(MINUTE).format(new Date());
    }
    // 獲取當前秒
    public static String getSec() {
        return new SimpleDateFormat(SEC).format(new Date());
    }
    // 獲取昨天日期
    public static String getYestday() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        Date d = cal.getTime();
        return new SimpleDateFormat(DATETIME).format(d);// 獲取昨天日期
    }
    public static String getMonday() {
        Calendar calendar = new GregorianCalendar();
        // 取得本週一
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        return new SimpleDateFormat(DATETIME).format(calendar.getTime());// 獲取昨天日期
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章