一个小小的时间工具类


import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static java.util.Calendar.*;

public class DateUtil {

    /**
     * 日期转字符串
     */
    public static String dateToString(Date date, String formatStr) {
        String strTime = "";
        try {
            DateFormat df = new SimpleDateFormat(formatStr);
            strTime = df.format(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strTime;
    }

    /**
     * 日期转字符串
     * 20170723121117
     */
    public static String dateString(Date date) {

        return dateToString(date, "yyMMddHHmmss");
    }

    /**
     * 日期转字符串
     * 20170723121117
     */
    public static String dateStringZH(Date date) {

        return dateToString(date, "yyyy年MM月dd日HH点mm分ss秒");
    }

    /**
     * 判断日期是null或空
     */
    public static boolean isDateNotNullOrEmpty(Date date) {
        String str = DateUtil.dateToString(date, "yyyy-MM-dd HH:mm:ss");
        return str != null && !str.equals("");
    }

    /**
     * 字符串转换到时间格式
     *
     * @param dateStr   需要转换的字符串
     * @param formatStr 需要格式的目标字符串 举例 yyyy-MM-dd
     * @return Date 返回转换后的时间
     * @throws ParseException 转换异常
     */
    public static Date stringToDate(String dateStr, String formatStr) {
        DateFormat sdf = new SimpleDateFormat(formatStr);
        Date date = null;
        try {
            date = sdf.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }


    /**
     * 取得系统时间
     */
    public static String getSystemTime() {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return df.format(new Date());
    }

    /**
     * 取得系统日期
     */
    public static String getSystemDate() {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        return df.format(new Date());
    }

    /**
     * 系统时间加减
     */
    public static String getOpeDate(String date, int dayNum) {
        Date dt = null;
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        try {
            dt = df.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        GregorianCalendar gc = new GregorianCalendar();
        assert dt != null;
        gc.setTime(dt);
        gc.add(Calendar.DATE, dayNum);
        return String.valueOf(df.format(gc.getTime()));
    }

    /**
     * 取得系统时间
     */
    public static String getShortSystemTime() {
        DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        return df.format(new Date());
    }


    /**
     * 取得系统短日期,yymmdd
     */
    public static String getShortSystemDate() {
        DateFormat df = new SimpleDateFormat("yyyyMMdd");
        return df.format(new Date());
    }


    /**
     * 获取某个时间段的所有天数集合(包含起始日期与终止日期)
     */
    public static List<String> getDayList(String starDate, String endDate) {
        String dateFormat = "yyyy-MM-dd";
        SimpleDateFormat format = new SimpleDateFormat(dateFormat);
        List<String> dayList = new ArrayList<>();
        if (starDate.equals(endDate)) {
            dayList.add(starDate);
        } else if (starDate.compareTo(endDate) < 0) {
            while (starDate.compareTo(endDate) <= 0) {
                dayList.add(starDate);
                try {
                    long l = stringToDate(starDate, "yyyy-MM-dd").getTime();
                    starDate = format.format(l + 3600 * 24 * 1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            dayList.add(endDate);
        }
        return dayList;
    }

    private static DateFormat dateFormat;

    private static Calendar calendar = getInstance();

    /**
     * 日期转换
     *
     * @param date      日期
     * @param dateStyle 日期格式
     * @return 转换后的日期字符串
     */
    public static String toString(Date date, DateStyle dateStyle) {
        dateFormat = new SimpleDateFormat(dateStyle.getValue());
        return dateFormat.format(date);
    }

    /**
     * 日期转换
     *
     * @param date      日期
     * @param dateStyle 日期格式
     * @return 转换后的日期字符串
     */
    public static String toString(Long date, DateStyle dateStyle) {
        dateFormat = new SimpleDateFormat(dateStyle.getValue());
        return dateFormat.format(new Date(date));
    }

    /**
     * 日期转换
     *
     * @param date 日期
     * @return 转换后的日期
     */
    public static Long toLong(Date date) {
        return date.getTime();
    }

    /**
     * 日期转换
     *
     * @param date 日期
     * @return 转换后的日期字符串
     */
    public static Date toDate(Long date) {
        return new Date(date);
    }

    /**
     * @return 得到当前日期
     */
    public static Long getNowDate() {
        return System.currentTimeMillis();
    }

    /**
     * 获取日期中的某数值。如获取月份
     *
     * @param date     日期
     * @param dateType 日期格式
     * @return 数值
     */
    private static int getInteger(Date date, int dateType) {
        Calendar calendar = getInstance();
        calendar.setTime(date);
        return calendar.get(dateType);
    }


    /**
     * 增加日期中某类型的某数值。如增加日期
     *
     * @param date     日期
     * @param dateType 类型
     * @param amount   数值
     * @return 计算后日期
     */
    private static Date addInteger(Date date, int dateType, int amount) {
        Date myDate = null;
        if (date != null) {
            Calendar calendar = getInstance();
            calendar.setTime(date);
            calendar.add(dateType, amount);
            myDate = calendar.getTime();
        }
        return myDate;
    }


    /**
     * 增加日期的年份。失败返回null。
     *
     * @param date       日期
     * @param yearAmount 增加数量。可为负数
     * @return 增加年份后的日期
     */
    public static Date addYear(Date date, int yearAmount) {
        return addInteger(date, YEAR, yearAmount);
    }

    /**
     * 增加日期的月份。失败返回null。
     *
     * @param date       日期
     * @param yearAmount 增加数量。可为负数
     * @return 增加月份后的日期
     */
    public static Date addMonth(Date date, int yearAmount) {
        return addInteger(date, MONTH, yearAmount);
    }

    /**
     * 增加日期的天数。失败返回null。
     *
     * @param date      日期
     * @param dayAmount 增加数量。可为负数
     * @return 增加天数后的日期
     */
    public static Date addDay(Date date, int dayAmount) {
        return addInteger(date, DATE, dayAmount);
    }

    /**
     * 增加日期的小时。失败返回null。
     *
     * @param date       日期
     * @param hourAmount 增加数量。可为负数
     * @return 增加小时后的日期
     */
    public static Date addHour(Date date, int hourAmount) {
        return addInteger(date, HOUR_OF_DAY, hourAmount);
    }

    /**
     * 增加日期的分钟。失败返回null。
     *
     * @param date         日期字符串
     * @param minuteAmount 增加数量。可为负数
     * @return 增加分钟后的日期字符串
     */
    public static Date addMinute(Date date, int minuteAmount) {
        return addInteger(date, MINUTE, minuteAmount);
    }

    /**
     * 增加日期的秒钟。失败返回null。
     *
     * @param date         日期字符串
     * @param secondAmount 增加数量。可为负数
     * @return 增加秒钟后的日期字符串
     */
    public static Date addSecond(Date date, int secondAmount) {
        return addInteger(date, SECOND, secondAmount);
    }

    /**
     * 获取日期的年份。失败返回0。
     *
     * @param date 日期字符串
     * @return 年份
     */
    public static int getYear(Date date) {
        return getInteger(date, YEAR);
    }

    /**
     * 获取日期的月份。失败返回0。
     *
     * @param date 日期字符串
     * @return 月份
     */
    public static int getMonth(Date date) {
        return getInteger(date, MONTH);
    }

    /**
     * 获取日期的天数。失败返回0。
     *
     * @param date 日期
     * @return      */
    public static int getDay(Date date) {
        return getInteger(date, DATE);
    }

    /**
     * 获取日期的小时。失败返回0。
     *
     * @param date 日期
     * @return 小时
     */
    public static int getHour(Date date) {
        return getInteger(date, HOUR_OF_DAY);
    }

    /**
     * 获取日期的分钟。失败返回0。
     *
     * @param date 日期
     * @return 分钟
     */
    public static int getMinute(Date date) {
        return getInteger(date, MINUTE);
    }


    /**
     * 获取日期的秒钟。失败返回0。
     *
     * @param date 日期
     * @return 秒钟
     */
    public static int getSecond(Date date) {
        return getInteger(date, SECOND);
    }

    /**
     * 获取日期。默认yyyy-MM-dd格式。失败返回null。
     *
     * @param date 日期
     * @return 日期
     */
    public static String getDate(Date date) {
        return toString(date, DateStyle.YYYY_MM_DD);
    }


    //获取当天的开始时间
    public static Date getDayBegin() {
        Calendar cal = new GregorianCalendar();
        cal.set(HOUR_OF_DAY, 0);
        cal.set(MINUTE, 0);
        cal.set(SECOND, 0);
        cal.set(MILLISECOND, 0);
        return cal.getTime();
    }

    //获取当天的结束时间
    public static Date getDayEnd() {
        Calendar cal = new GregorianCalendar();
        cal.set(HOUR_OF_DAY, 23);
        cal.set(MINUTE, 59);
        cal.set(SECOND, 59);
        return cal.getTime();
    }

    //获取昨天的开始时间
    public static Date getBeginDayOfYesterday() {
        Calendar cal = new GregorianCalendar();
        cal.setTime(getDayBegin());
        cal.add(DAY_OF_MONTH, -1);
        return cal.getTime();
    }

    //获取昨天的结束时间
    public static Date getEndDayOfYesterDay() {
        Calendar cal = new GregorianCalendar();
        cal.setTime(getDayEnd());
        cal.add(DAY_OF_MONTH, -1);
        return cal.getTime();
    }

    //获取明天的开始时间
    public static Date getBeginDayOfTomorrow() {
        Calendar cal = new GregorianCalendar();
        cal.setTime(getDayBegin());
        cal.add(DAY_OF_MONTH, 1);

        return cal.getTime();
    }

    //获取明天的结束时间
    public static Date getEndDayOfTomorrow() {
        Calendar cal = new GregorianCalendar();
        cal.setTime(getDayEnd());
        cal.add(DAY_OF_MONTH, 1);
        return cal.getTime();
    }

    //获取本周的开始时间
    public static Long getBeginDayOfWeek() {
        Date date = new Date();
        Calendar cal = getInstance();
        cal.setTime(date);
        int dayofweek = cal.get(DAY_OF_WEEK);
        if (dayofweek == 1) {
            dayofweek += 7;
        }
        cal.add(DATE, 2 - dayofweek);
        return getDayStartTime(cal.getTime());
    }

    //获取本周的结束时间
    public static Long getEndDayOfWeek() {
        Calendar cal = getInstance();
        cal.setTime(toDate(getBeginDayOfWeek()));
        cal.add(DAY_OF_WEEK, 6);
        Date weekEndSta = cal.getTime();
        return getDayEndTime(weekEndSta);
    }

    //获取本月的开始时间
    public static Long getBeginDayOfMonth() {
        Calendar calendar = getInstance();
        calendar.set(getNowYear(), getNowMonth() - 1, 1);
        return getDayStartTime(calendar.getTime());
    }

    //获取本月的结束时间
    public static Long getEndDayOfMonth() {
        Calendar calendar = getInstance();
        calendar.set(getNowYear(), getNowMonth() - 1, 1);
        int day = calendar.getActualMaximum(5);
        calendar.set(getNowYear(), getNowMonth() - 1, day);
        return getDayEndTime(calendar.getTime());
    }

    //获取本年的开始时间
    public static Long getBeginDayOfYear() {
        Calendar cal = getInstance();
        cal.set(YEAR, getNowYear());
        // cal.set
        cal.set(MONTH, JANUARY);
        cal.set(DATE, 1);

        return getDayStartTime(cal.getTime());
    }

    //获取本年的结束时间
    public static Long getEndDayOfYear() {
        Calendar cal = getInstance();
        cal.set(YEAR, getNowYear());
        cal.set(MONTH, DECEMBER);
        cal.set(DATE, 31);
        return getDayEndTime(cal.getTime());
    }

    //获取某个日期的开始时间
    public static Long getDayStartTime(Date d) {
        Calendar calendar = getInstance();
        if (null != d) calendar.setTime(d);
        calendar.set(calendar.get(YEAR), calendar.get(MONTH), calendar.get(DAY_OF_MONTH), 0, 0, 0);
        calendar.set(MILLISECOND, 0);
        return calendar.getTimeInMillis();
    }

    //获取某个日期的结束时间
    public static Long getDayEndTime(Date d) {
        Calendar calendar = getInstance();
        if (null != d) calendar.setTime(d);
        calendar.set(calendar.get(YEAR), calendar.get(MONTH), calendar.get(DAY_OF_MONTH), 23, 59, 59);
        calendar.set(MILLISECOND, 999);
        return calendar.getTimeInMillis();
    }

    //获取今年是哪一年
    public static Integer getNowYear() {
        Date date = new Date();
        GregorianCalendar gc = (GregorianCalendar) getInstance();
        gc.setTime(date);
        return gc.get(Calendar.YEAR);
    }

    //获取本月是哪一月
    public static int getNowMonth() {
        Date date = new Date();
        GregorianCalendar gc = (GregorianCalendar) getInstance();
        gc.setTime(date);
        return gc.get(Calendar.MONTH) + 1;
    }

    //两个日期相减得到的天数
    public static int getDiffDays(Date beginDate, Date endDate) {

        if (beginDate == null || endDate == null) {
            throw new IllegalArgumentException("getDiffDays param is null!");
        }

        long diff = (endDate.getTime() - beginDate.getTime())
                / (1000 * 60 * 60 * 24);

        return new Long(diff).intValue();
    }

    //两个日期相减得到的毫秒数
    public static long dateDiff(Date beginDate, Date endDate) {
        long date1ms = beginDate.getTime();
        long date2ms = endDate.getTime();
        return date2ms - date1ms;
    }

    //获取两个日期中的最大日期
    public static Date max(Date beginDate, Date endDate) {
        if (beginDate == null) {
            return endDate;
        }
        if (endDate == null) {
            return beginDate;
        }
        if (beginDate.after(endDate)) {
            return beginDate;
        }
        return endDate;
    }

    //获取两个日期中的最小日期
    public static Date min(Date beginDate, Date endDate) {
        if (beginDate == null) {
            return endDate;
        }
        if (endDate == null) {
            return beginDate;
        }
        if (beginDate.after(endDate)) {
            return endDate;
        }
        return beginDate;
    }

    //返回某月该季度的第一个月
    public static Date getFirstSeasonDate(Date date) {
        final int[] SEASON = {1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4};
        Calendar cal = getInstance();
        cal.setTime(date);
        int sean = SEASON[cal.get(MONTH)];
        cal.set(MONTH, sean * 3 - 3);
        return cal.getTime();
    }

    //返回某个日期下几天的日期
    public static Date getNextDay(Date date, int i) {
        Calendar cal = new GregorianCalendar();
        cal.setTime(date);
        cal.set(DATE, cal.get(DATE) + i);
        return cal.getTime();
    }

    //返回某个日期前几天的日期
    public static Date getFrontDay(Date date, int i) {
        Calendar cal = new GregorianCalendar();
        cal.setTime(date);
        cal.set(DATE, cal.get(DATE) - i);
        return cal.getTime();
    }

    //获取某年某月到某年某月按天的切片日期集合(间隔天数的日期集合)
    public static List getTimeList(int beginYear, int beginMonth, int endYear,
                                   int endMonth, int k) {
        List<List> list = new ArrayList<>();
        if (beginYear == endYear) {
            for (int j = beginMonth; j <= endMonth; j++) {
                list.add(getTimeList(beginYear, j, k));

            }
        } else {
            {
                for (int j = beginMonth; j < 12; j++) {
                    list.add(getTimeList(beginYear, j, k));
                }

                for (int i = beginYear + 1; i < endYear; i++) {
                    for (int j = 0; j < 12; j++) {
                        list.add(getTimeList(i, j, k));
                    }
                }
                for (int j = 0; j <= endMonth; j++) {
                    list.add(getTimeList(endYear, j, k));
                }
            }
        }
        return list;
    }

    //获取某年某月按天切片日期集合(某个月间隔多少天的日期集合)
    public static List getTimeList(int beginYear, int beginMonth, int k) {
        List<Date> list = new ArrayList<>();
        Calendar begincal = new GregorianCalendar(beginYear, beginMonth, 1);
        int max = begincal.getActualMaximum(DATE);
        for (int i = 1; i < max; i = i + k) {
            list.add(begincal.getTime());
            begincal.add(DATE, k);
        }
        begincal = new GregorianCalendar(beginYear, beginMonth, max);
        list.add(begincal.getTime());
        return list;
    }

}

猜你喜欢

转载自blog.csdn.net/qq_32778043/article/details/80741498