java 日期工具类 DateUtil

DateUtil是一个Java类,用于日期和时间的处理,包括日期格式化、时间差计算、日期转换、年龄计算、星期获取、日期加减等操作。该类提供了静态方法,方便对日期进行各种常见操作。
摘要由CSDN通过智能技术生成

/**
 * 字符串-日期,日期计算,时间差值工具类
 * 
 */
public class DateUtil {
    public static final long HOUR = 60 * 60 * 1000;

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

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

    private static final String TIME_PATTERN = "HH:mm";

    private static final long DAY = 24 * HOUR;

 /**
     * 默认格式化成: yyyy-MM-dd
     * 
     * @param time
     * @return
     */
    public static String formatDate(long time) {
        SimpleDateFormat df = null;
        String returnValue = "";
        if (time > 0) {
            df = new SimpleDateFormat(FORMATER);
            returnValue = df.format(time);
        }
        return (returnValue);
    }

    /**
     * 默认格式化成: yyyy-MM-dd
     * 
     * @param aDate
     * @return
     */
    public static String formatDate(Date aDate) {
        SimpleDateFormat df = null;
        String returnValue = "";
        if (aDate != null) {
            df = new SimpleDateFormat(FORMATER);
            returnValue = df.format(aDate);
        }
        return (returnValue);
    }

/**
     * This method generates a string representation of a date/time in the format you specify on input
     * 
     * @param aMask   the date pattern the string is in
     * @param strDate a string representation of a date
     * @return a converted Date object
     * @see java.text.SimpleDateFormat
     * @throws ParseException when String doesn't match the expected format
     */
    public static Date convert(String aMask, String strDate) {
        SimpleDateFormat df;
        Date date = null;
        df = new SimpleDateFormat(aMask);
        try {
            date = df.parse(strDate);
        } catch (ParseException pe) {
            pe.printStackTrace();
        }
        return date;
    }

    /**
     * 生成一个字符串类型的时间,根据long类型的时间
     * 
     * @Author JiangHan
     * @param format the date pattern the string is in
     * @param time   时间
     * @return
     */
    public static String formatDate(String format, long time) {
        SimpleDateFormat df = null;
        String returnValue = "";
        if (time > 0) {
            df = new SimpleDateFormat(format);
            returnValue = df.format(time);
        }
        return (returnValue);
    }

    /**
     * This method generates a string representation of a date's date/time in the format you specify on input
     * 
     * @param aMask the date pattern the string is in
     * @param aDate a date object
     * @return a formatted string representation of the date
     * @see java.text.SimpleDateFormat
     */
    public static String formatDate(String format, Date aDate) {
        SimpleDateFormat df = null;
        String returnValue = "";
        if (aDate != null) {
            df = new SimpleDateFormat(format);
            returnValue = df.format(aDate);
        }
        return (returnValue);
    }  

    /**
     * This method returns the current date time in the format: MM/dd/yyyy HH:MM a
     * 
     * @param theTime the current time
     * @return the current date/time
     */
    public static String toDateTimeString(Date theTime) {
        return formatDate(TIME_PATTERN, theTime);
    }

    /**
     * This method generates a string representation of a date's date/time in the format you specify on input
     * 
     * @param aMask the date pattern the string is in
     * @param aDate a date object
     * @return a formatted string representation of the date
     * @see java.text.SimpleDateFormat
     */
    public static String getDateTime(String aMask, Date aDate) {
        SimpleDateFormat df = null;
        String returnValue = "";

        if (aDate != null) {
            df = new SimpleDateFormat(aMask);
            returnValue = df.format(aDate);
        }

        return (returnValue);
    }

    /**
     * return age
     * 
     * @param birthday
     * @return
     */
    public static String getAge(Date birthday) {
        int year = 0;
        int month = 0;
        int day = 0;
        if (birthday != null) {
            Calendar date = Calendar.getInstance();
            Calendar now = Calendar.getInstance();
            date.setTime(birthday);
            day = now.get(Calendar.DAY_OF_MONTH) - date.get(Calendar.DAY_OF_MONTH);
            month = now.get(Calendar.MONTH) - date.get(Calendar.MONTH);
            year = now.get(Calendar.YEAR) - date.get(Calendar.YEAR);
            if (day < 0) {
                month -= 1;
                now.add(Calendar.MONTH, -1);
                day = day + now.getActualMaximum(Calendar.DAY_OF_MONTH);
            }
            if (month < 0) {
                month = (month + 12) % 12;
                year--;
            }
        }

        if (year == 0 && month != 0) {
            return String.valueOf(month) + "月";
        } else if ((year == 0 && month == 0)) {
            return String.valueOf(day) + "天";
        } else {
            return String.valueOf(year) + "岁";
        }
    }

    /**
     * 根据日期获取时星期几 如果date为null,返回-1
     * 
     * @param date
     * @return
     */
    public static String getWeekByDate(Date date) {

        if (ObjectUtil.isNullOrEmpty(date)) {
            return "-1";
        }
        Calendar calendar = Calendar.getInstance();// 获得一个日历
        calendar.setTime(date);// 设置当前时间,月份是从0月开始计算
        int number = calendar.get(Calendar.DAY_OF_WEEK);// 星期表示1-7,是从星期日开始,
        String[] str = { "", "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", };

        return str[number];
    }

    /**
     * 获取day天后日期类型
     * 
     * @param date
     * @param day
     * @return
     */
    public static Date getAfterDay(Date date, int day) {
        if (null == date)
            return null;
        if (day == 0)
            return date;
        return new Date(date.getTime() + day * 24 * 60 * 60 * 1000);
    }

    /**
     * 获取day天后日期类型
     * 
     * @param date
     * @param day
     * @return
     */
    public static Date convertDate(String fmt, Date aDate) {
        return convert(fmt, getDateTime(fmt, aDate));
    }

    public static Date parseSimpleDate(String dateStr, String formater) {
        if (null == dateStr || dateStr.trim().length() < 1) {
            return null;
        }
        SimpleDateFormat format = new SimpleDateFormat(formater.trim());
        try {
            return format.parse(dateStr);
        } catch (ParseException e) {
            return null;
        }
    }

    public static Date parseDateString(String dateStr) {
        return parseSimpleDate(dateStr, FORMATER);
    }

    /**
     * 获取字符串类型的日期 默认类型: yy-DD-mm
     * 
     * @Author JiangHan
     * @param date
     * @return
     */
    public static String getStringByDate(Date date) {
        SimpleDateFormat format = new SimpleDateFormat(FORMATER);
        return format.format(date);
    }

    /**
     * 根据年龄计算出生日期
     * 
     * @param age
     * @param type
     * @return
     */
    public static Date getBirthdayByAge(int age) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.YEAR, 0 - age);
        return cal.getTime();
    }

    /**
     * 根据年龄计算出生年份
     * 
     * @param age
     * @param type
     * @return
     */
    public static int getBirthYearByAge(int age) {
        Calendar cal = Calendar.getInstance();
        return cal.get(Calendar.YEAR) - age;
    }

    /**
     * 根据生日获得年龄,算出的周岁需要加1
     * 
     * @param birthday
     * @return
     */
    public static int getAgeByBirthday(Date birthday) {
        if (null == birthday) {
            return 0;
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(birthday);
        return Calendar.getInstance().get(Calendar.YEAR) - cal.get(Calendar.YEAR) + 1;
    }

    public static Date getDateByYearMonthDay(int year, int month, int day) {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.YEAR, year);
        c.set(Calendar.MONTH, month);
        c.set(Calendar.DAY_OF_MONTH, day);

        return c.getTime();
    }

    /**
     * 获取两个日期间隔天数
     * 
     * @param before
     * @param after
     * @return
     */
    public static int getBetweenDays(Date before, Date after) {
        long days = Math.abs((before.getTime() - after.getTime())) / DAY;
        return (int) days + 1;
    }

    /**
     * 获取两个日期间隔天数
     * 
     * @param start 开始日期
     * @param end   结束日期
     * @return 两个日期间隔天数
     */
    public static int getDaysBetween(Calendar start, Calendar end) {
        if (start.after(end)) {// 开始时间在结束时间之后,则互换
            Calendar swap = start;
            start = end;
            end = swap;
        }
        int days = end.get(Calendar.DAY_OF_YEAR) - start.get(Calendar.DAY_OF_YEAR);
        int y2 = end.get(Calendar.YEAR);
        if (start.get(Calendar.YEAR) != y2) {
            start = (Calendar) start.clone();
            do {
                days += start.getActualMaximum(Calendar.DAY_OF_YEAR);
                start.add(Calendar.YEAR, 1);
            } while (start.get(Calendar.YEAR) != y2);
        }
        return days + 1;
    }

    /**
     * 将Data中时间部分变为0
     * 
     * @param date
     * @return
     */
    public static Date makeTimeToZero(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        makeTimeToZero(calendar);
        return calendar.getTime();
    }

    public static void makeTimeToZero(Calendar calendar) {
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.clear(Calendar.MINUTE);
        calendar.clear(Calendar.SECOND);
        calendar.clear(Calendar.MILLISECOND);
    }

    /**
     * 将Data中时间部分变为最大
     * 
     * @param date
     * @return
     */
    public static Date makeDateToZero(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        makeDateToZero(calendar);
        return calendar.getTime();
    }

    public static void makeDateToZero(Calendar calendar) {
        calendar.set(Calendar.MONTH, Calendar.JANUARY);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        makeTimeToZero(calendar);
    }

    /**
     * 将Data中时间部分变为最大
     * 
     * @param date
     * @return
     */
    public static Date makeDateToMax(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        makeDateToMax(calendar);
        return calendar.getTime();
    }

    public static void makeDateToMax(Calendar calendar) {
        calendar.set(Calendar.MONTH, Calendar.DECEMBER);
        calendar.set(Calendar.DAY_OF_MONTH, 31);
        makeTimeToZero(calendar);
    }

    /**
     * 将Data中时间部分变为最大
     * 
     * @param date
     * @return
     */
    public static Date nextMonthFirstDay(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        nextMonthFirstDay(calendar);
        return calendar.getTime();
    }

    public static void nextMonthFirstDay(Calendar calendar) {
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + 1);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        makeTimeToZero(calendar);
    }

    /**
     * 将Data中时间部分变为最大
     * 
     * @param date
     * @return
     */
    public static Date makeTimeToMax(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        makeTimeToMax(calendar);
        return calendar.getTime();
    }

    public static void makeTimeToMax(Calendar calendar) {
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
    }

    /**
     * 获取日期
     * 
     * @return
     */
    public static Date getCurrentWithoutTime() {
        Date current = new Date();
        return makeTimeToZero(current);
    }

    /**
     * 生成日期字符串列表
     * 
     * @param fromDate
     * @param days
     * @return
     */
    public static List<String> makeDayList(Date fromDate, int days) {
        return makeDayList(fromDate, "yyyy-MM-dd", days);
    }

    /**
     * 生成日期字符串列表
     * 
     * @param fromDate
     * @param pattern
     * @param days
     * @return
     */
    public static List<String> makeDayList(Date fromDate, String pattern, int days) {
        List<String> weeks = new ArrayList<String>();
        for (int i = 0; i < days; i++) {
            weeks.add(DateUtil.formatDate(pattern, add(fromDate, Calendar.DAY_OF_MONTH, i)));
        }
        return weeks;
    }

    /**
     * 计算周数
     * 
     * @param fromDate
     * @param pattern
     * @param days
     * @return
     */
    public static int getWeeks(int days) {
        return days % 7 == 0 ? days / 7 : days / 7 + 1;
    }

    /**
     * 获取份的日期范围
     * 
     * @param month
     * @return
     */
    public static Date[] getDateRangeByMonth(int month) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MONTH, month);
        calendar.set(Calendar.MONTH, month);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        makeTimeToZero(calendar);
        Date startDate = calendar.getTime();
        int maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), maxDay, 23, 59, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        Date endDate = calendar.getTime();
        return new Date[] { startDate, endDate };
    }

    /**
     * 返回季节范围
     * 
     * @param season
     * @return
     */
    public static Date[] getDateRangeBySeason(int season) {
        // 一:11号,331号
        // 二:41号,630号
        // 三:71号,930号
        // 四:101号,1231号

        Date startDate = null;
        Date endDate = null;

        int month = 0;
        int monthEnd = 0;
        int day = 1;
        switch (season) {
        case 1:
            month = Calendar.JANUARY;
            monthEnd = Calendar.MARCH;
            day = 31;
            break;
        case 2:
            month = Calendar.APRIL;
            monthEnd = Calendar.JUNE;
            day = 30;
            break;
        case 3:
            month = Calendar.JULY;
            monthEnd = Calendar.SEPTEMBER;
            day = 30;
            break;

        default:
            month = Calendar.OCTOBER;
            monthEnd = Calendar.DECEMBER;
            day = 31;
            break;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MONTH, month);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        makeTimeToZero(calendar);
        startDate = calendar.getTime();
        calendar.set(Calendar.MONTH, monthEnd);
        calendar.set(Calendar.DAY_OF_MONTH, day);
        makeTimeToMax(calendar);
        endDate = calendar.getTime();
        return new Date[] { startDate, endDate };
    }

    /**
     * 返回年日期范围
     * 
     * @param year
     * @return
     */
    public static Date[] getDateRangeByYear(int year) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, Calendar.JANUARY);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        makeTimeToZero(calendar);
        Date startDate = calendar.getTime();
        calendar.set(Calendar.MONTH, Calendar.DECEMBER);
        calendar.set(Calendar.DAY_OF_MONTH, 31);
        makeTimeToMax(calendar);
        Date endDate = calendar.getTime();
        return new Date[] { startDate, endDate };
    }

    /**
     * 返回统计年范围
     * 
     * @param year
     * @return
     */
    public static Date[] getDateRangeByYearStatistics(int year) {
        // 统计年
        // 10 月 1 日到次年9月 30日
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year - 1);
        calendar.set(Calendar.MONTH, Calendar.OCTOBER);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        makeTimeToZero(calendar);
        Date startDate = calendar.getTime();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, Calendar.SEPTEMBER);
        calendar.set(Calendar.DAY_OF_MONTH, 30);
        makeTimeToMax(calendar);
        Date endDate = calendar.getTime();
        return new Date[] { startDate, endDate };
    }

    /**
     * 返回日期范围
     * 
     * @param start
     * @param end
     * @return
     */
    public static Date[] getDateRange(String start, String end) {
        Date startDate = parseDateString(start);
        if (null != startDate) {
            startDate = makeTimeToZero(startDate);
        }
        Date endDate = parseDateString(end);
        if (null != endDate) {
            endDate = makeTimeToMax(endDate);
        }
        return new Date[] { startDate, endDate };
    }

    /**
     * 返回年龄日期范围
     * 
     * @param start
     * @param end
     * @return
     */
    public static Date[] getDateRangeByAge(String start, String end) {
        int startAge = 0;
        try {
            startAge = Integer.parseInt(start);
        } catch (Exception e) {
            startAge = -1;
        }

        int endAge = 0;
        try {
            endAge = Integer.parseInt(end);
        } catch (Exception e) {
            endAge = -1;
        }

        Date startDate = null;
        Date endDate = null;
        if (-1 != startAge) {
            endDate = makeDateToMax(getBirthdayByAge(startAge));
        }

        if (-1 != endAge) {
            startDate = makeDateToZero(getBirthdayByAge(endAge));
        }
        return new Date[] { startDate, endDate };
    }

    /**
     * 季节大写
     * 
     * @return
     */
    public static Map<Integer, String> getSeasonMap() {
        Map<Integer, String> month = new HashMap<Integer, String>();
        month.put(1, "一");
        month.put(2, "二");
        month.put(3, "三");
        month.put(4, "四");
        return month;
    }

    /**
     * 月份大写
     * 
     * @return
     */
    public static Map<Integer, String> getMonthMap() {
        Map<Integer, String> month = new HashMap<Integer, String>();
        month.put(Calendar.JANUARY, "一");
        month.put(Calendar.FEBRUARY, "二");
        month.put(Calendar.MARCH, "三");
        month.put(Calendar.APRIL, "四");
        month.put(Calendar.MAY, "五");
        month.put(Calendar.JUNE, "六");
        month.put(Calendar.JULY, "七");
        month.put(Calendar.AUGUST, "八");
        month.put(Calendar.SEPTEMBER, "九");
        month.put(Calendar.OCTOBER, "十");
        month.put(Calendar.NOVEMBER, "十一");
        month.put(Calendar.DECEMBER, "十二");
        return month;
    }

    /**
     * 获取指定之前年列表
     * 
     * @param count
     * @return
     */
    public static List<Integer> getBeforeYears(int count) {
        List<Integer> years = new ArrayList<Integer>();
        int year = getCurrentYear();
        for (int i = 0; i <= 8; i++) {
            years.add(year--);
        }
        return years;
    }

    /**
     * 日期计算
     * 
     * @param date
     * @param calendarField
     * @param amount
     * @return
     */
    public static Date add(Date date, int calendarField, int amount) {
        if (date == null) {
            return null;
        }
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(calendarField, amount);
        return c.getTime();
    }

    public static Date getDateByYear(int year) {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.YEAR, year);
        // c.set(Calendar.MONTH, month);
        // c.set(Calendar.DAY_OF_MONTH, day);
        return c.getTime();
    }

    /**
     * 当前年
     * 
     * @return
     */
    public static int getCurrentYear() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        return year;
    }

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

    /**
     * 当前日
     * 
     * @return
     */
    public static int getCurrentDay() {
        Calendar calendar = Calendar.getInstance();
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        return day;
    }

    /**
     * 判断当前时间是否在给定的两个时间内,如果参数为null的话,默认为在里面
     * 
     * @param start 开始时间
     * @param end   结束时间
     * @return
     */
    public static boolean isBetweenDays(Date start, Date end) {
        boolean[] result = new boolean[] { true, true };
        if (null != start && start.getTime() > System.currentTimeMillis()) {
            result[0] = false;
        }
        if (null != end && end.getTime() < System.currentTimeMillis()) {
            result[1] = false;
        }
        return result[0] && result[1];
    }

    /**
     * 判断是否闰年
     * 
     * @param year
     * @return
     */
    public static boolean isLeapYear(int year) {
        boolean flag = false;
        if ((year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0))) {
            flag = true;
        }
        return flag;
    }

    /**
     * 根据年月,获取月天数
     * 
     * @param year
     * @param month
     */
    public static int monthDays(int year, int month) {
        int dayNum = 28;
        switch (month) {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
            dayNum = 31;
            break;
        case 4:
        case 6:
        case 9:
        case 11:
            dayNum = 30;
            break;
        case 2:
            if (DateUtil.isLeapYear(year))
                dayNum = 29;
            break;
        default:
            break;
        }
        return dayNum;
    }

    /**
     * 补全给定的开始和结束日期内的所有日期,并按照日期增长顺序排序返回
     * 
     * @param startDate
     * @param endDate
     * @return
     */
    public static Set<String> completeDateStr(String startDate, String endDate) {
        Set<String> result = new TreeSet<String>();
        Date sd = parseDateString(startDate);
        Date ed = parseDateString(endDate);
        while (sd.getTime() < ed.getTime()) {
            result.add(formatDate(sd));
            sd = getAfterDay(sd, 1);
        }
        return result;
    }

    /**
     * 补全给定的开始和结束日期内的所有日期,并按照日期增长顺序排序返回
     * 
     * @param startDate
     * @param endDate
     * @return
     */
    public static Set<String> completeDateStr(Date startDate, Date endDate) {
        return completeDateStr(formatDate(startDate), formatDate(endDate));
    }

    public static String[] MONTH_DESC = new String[] { "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEPT", "OCT", "NOV", "DEC" };

    /**
     * 当前月份英文简写
     * 
     * @return
     */
    public static String getCurMonthDesc() {
        Calendar c = Calendar.getInstance();
        int month = c.get(Calendar.MONTH);
        return MONTH_DESC[month];
    }
}

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

长青风

赏一块,发大财!赏两块,惹人爱

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值