Java 日期处理工具类

package com.zhengyuxiao.toolbox.date;

import java.util.Calendar;
import java.util.Date;

/**
 * @author xzy
 * @date 2020-09-14 14:05
 * 说明:日期处理
 */
public class CalendarUtils {
    /**
     * Get a instance of Calendar by given Date instance.
     *
     * @param date the date want to convert
     * @return a instance of Calendar by given Date instance
     */
    public static Calendar date2Calendar(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar;
    }

    /**
     * Get a instance of Date by given Calendar instance.
     *
     * @param calendar the calendar want to convert
     * @return a instance of Date by given Calendar instance.
     */
    public static Date calendar2Date(Calendar calendar) {
        return calendar.getTime();
    }

    /**
     * Get the day of the week represented by this date.
     *
     * @param date -
     * @return 0:Sunday 1:Monday 2:Tuesday 3:Wednesday 4:Thursday 5:Friday 6:Saturday
     */
    public static int getDayOfWeek(Date date) {
        Calendar calendar = date2Calendar(date);
        return calendar.get(Calendar.DAY_OF_WEEK);
    }

    /**
     * Get the day of the year represented by this date.
     *
     * @param date -
     * @return the day of the year represented by this date.The first day of the year has value 1.
     */
    public static int getDayOfYear(Date date) {
        Calendar calendar = date2Calendar(date);
        return calendar.get(Calendar.DAY_OF_YEAR);
    }

    /**
     * Get number of the days for specified month.
     *
     * @param date -
     * @return - number of the days for specified month。
     */
    public static int getNumberOfTheDaysForSpecifiedMonth(Date date) {
        Calendar calendar = date2Calendar(date);
        return getNumberOfTheDaysForSpecifiedMonth(calendar);
    }

    /**
     * Get number of the days for specified month.
     *
     * @param calendar -
     * @return - number of the days for specified month。
     */
    public static int getNumberOfTheDaysForSpecifiedMonth(Calendar calendar) {
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

    /**
     * Get Number Of The Days For Specified Month Exclude Weekend.
     *
     * @param calendar -
     * @return - The Days For Specified Month Exclude Weekend.
     */
    public static int getNumberOfTheDaysForSpecifiedMonthExcludeWeekend(Calendar calendar) {
        int numberOfTheDaysForSpecifiedMonthExcludeWeekend = 0;

        firstDayForSpecifiedMonth(calendar);
        int numberOfTheDaysForSpecifiedMonth = getNumberOfTheDaysForSpecifiedMonth(calendar);
        for (int i = 0; i < numberOfTheDaysForSpecifiedMonth; i++) {
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            if (!isWeekend(calendar)) {
                numberOfTheDaysForSpecifiedMonthExcludeWeekend++;
            }
        }

        return numberOfTheDaysForSpecifiedMonthExcludeWeekend;
    }

    /**
     * 计算两个日期间相差的天数。
     *
     * @param date1 - 日期1
     * @param date2 - 日期2
     * @return - 两个日期相差的天数。注意,本方法认为 “2020-01-01 23:59:59” 与 “2020-01-02 00:00:00”相差1天。
     */
    public static long getDaysOfDifference(Date date1, Date date2) {
        if (date1 == null || date2 == null) {
            throw new NullPointerException();
        }
        return getDaysOfDifference(date2Calendar(date1), date2Calendar(date2));
    }

    /**
     * 计算两个日期间相差的天数。
     *
     * @param cal1 - 日期1
     * @param cal2 - 日期2
     * @return - 两个日期相差的天数。注意,本方法认为 “2020-01-01 23:59:59” 与 “2020-01-02 00:00:00”相差1天。
     */
    public static long getDaysOfDifference(Calendar cal1, Calendar cal2) {
        if (cal1 == null || cal2 == null) {
            throw new NullPointerException();
        }
        cleanTime(cal1);
        cleanTime(cal2);

        // 1天 = 24小时 = 24*3600秒 = 24*3600*1000毫秒
        long dayOfDifference = (cal1.getTimeInMillis() - cal2.getTimeInMillis()) / (1000 * 3600 * 24);
        dayOfDifference = dayOfDifference < 0 ? -dayOfDifference : dayOfDifference;
        return dayOfDifference;
    }

    /**
     * Returns whether the two dates are the same day.
     *
     * @param date1 the date 1
     * @param date2 the date 2
     * @return whether the two dates are the same day.
     */
    public static boolean isSameDay(Date date1, Date date2) {
        if (date1 == null || date2 == null) {
            throw new NullPointerException();
        }
        return isSameDay(date2Calendar(date1), date2Calendar(date2));
    }

    /**
     * Returns whether the two dates are the same day.
     *
     * @param cal1 the date 1
     * @param cal2 the date 2
     * @return whether the two dates are the same day.
     */
    public static boolean isSameDay(Calendar cal1, Calendar cal2) {
        if (cal1 == null || cal2 == null) {
            throw new NullPointerException();
        }

        return (cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) &&
                cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
                cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR));
    }

    /**
     * Returns whether the specified date is weekend.
     *
     * @param date -
     * @return - true or false
     */
    public static boolean isWeekend(Date date) {
        Calendar calendar = date2Calendar(date);
        return isWeekend(calendar);
    }

    /**
     * Returns whether the specified date is weekend.
     *
     * @param calendar -
     * @return - true or false
     */
    public static boolean isWeekend(Calendar calendar) {
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        return dayOfWeek == Calendar.SUNDAY || dayOfWeek == Calendar.SATURDAY;
    }

    /**
     * 清洗时间——将时、分、秒、毫秒清零
     *
     * @param calendar - 待处理的日期
     */
    public static void cleanTime(Calendar calendar) {
        if (calendar == null) {
            throw new IllegalArgumentException("The date must not be null");
        }
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        calendar.getTime();
    }

    public static Date cleanTime(Date date) {
        Calendar calendar = date2Calendar(date);
        cleanTime(calendar);
        return calendar2Date(calendar);
    }

    /**
     * 清除日期——将年、月、日清零
     *
     * @param calendar - 待处理的日期
     */
    public static void cleanDate(Calendar calendar) {
        if (calendar == null) {
            throw new IllegalArgumentException("The date must not be null");
        }
        calendar.set(Calendar.YEAR, 0);
        calendar.set(Calendar.MONTH, 0);
        calendar.set(Calendar.DAY_OF_MONTH, 0);
        calendar.getTime();
    }

    public static Date cleanDate(Date date) {
        Calendar calendar = date2Calendar(date);
        cleanDate(calendar);
        return calendar2Date(calendar);
    }

    /**
     * 获取指定日期的“最初时刻”,即“yyyy-MM-dd 00:00:00:000”
     *
     * @param calendar - 待处理的日期
     */
    public static void firstMoment(Calendar calendar) {
        cleanTime(calendar);
    }

    public static Date firstMoment(Date date) {
        Calendar calendar = date2Calendar(date);
        firstMoment(calendar);
        return calendar2Date(calendar);
    }

    /**
     * 获取指定日期的“最终时刻”,即“yyyy-MM-dd 23:59:59:999”
     *
     * @param calendar - 待处理的日期
     */
    public static void lastMoment(Calendar calendar) {
        if (calendar == null) {
            throw new IllegalArgumentException("The date must not be null");
        }
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        calendar.getTime();
    }

    public static Date lastMoment(Date date) {
        Calendar calendar = date2Calendar(date);
        lastMoment(calendar);
        return calendar2Date(calendar);
    }

    /**
     * 获取指定日期所在月份的第一天
     *
     * @param calendar -
     */
    public static void firstDayForSpecifiedMonth(Calendar calendar) {
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.getTime();
    }

    /**
     * 获取指定日期所在月份的最后一天
     *
     * @param calendar -
     */
    public static void lastDayForSpecifiedMonth(Calendar calendar) {
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        calendar.getTime();
    }

    /**
     * 按照日期的计算规则,将指定日期的指定字段加上或减去指定的量。
     *
     * @param date   - 待修改的日期
     * @param field  - 待修改的日期字段(具体取值需要查询Calendar接口)
     * @param amount - 修改量
     * @return - 修改后的日期
     */
    public static Date add(Date date, int field, int amount) {
        if (date == null) {
            throw new IllegalArgumentException("The date must not be null");
        }

        Calendar calendar = date2Calendar(date);
        calendar.add(field, amount);
        return calendar2Date(calendar);
    }

    private CalendarUtils() {
    }

    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        System.out.println(calendar);

        calendar.set(Calendar.DAY_OF_MONTH, 1);
        System.out.println(calendar);

        calendar.getTime();
        System.out.println(calendar);
    }
}


package com.hexiang.utils; import java.text.SimpleDateFormat; import java.util.*; public class CalendarUtil { public static void main(String args[]) { System.out.println("First day of week is : " + new SimpleDateFormat("yyyy-MM-dd") .format(getFirstDateByWeek(new Date()))); System.out.println("Last day of week is : " + new SimpleDateFormat("yyyy-MM-dd") .format(getLastDateByWeek(new Date()))); System.out.println("First day of month is : " + new SimpleDateFormat("yyyy-MM-dd") .format(getFirstDateByMonth(new Date()))); System.out.println("Last day of month is : " + new SimpleDateFormat("yyyy-MM-dd") .format(getLastDateByMonth(new Date()))); } /** * 获得所在星期的第一天 */ public static Date getFirstDateByWeek(Date date) { Calendar now = Calendar.getInstance(); now.setTime(date); int today = now.get(Calendar.DAY_OF_WEEK); int first_day_of_week = now.get(Calendar.DATE) + 2 - today; // 星期一 now.set(Calendar.DATE, first_day_of_week); return now.getTime(); } /** * 获得所在星期的最后一天 */ public static Date getLastDateByWeek(Date date) { Calendar now = Calendar.getInstance(); now.setTime(date); int today = now.get(Calendar.DAY_OF_WEEK); int first_day_of_week = now.get(Calendar.DATE) + 2 - today; // 星期一 int last_day_of_week = first_day_of_week + 6; // 星期日 now.set(Calendar.DATE, last_day_of_week); return now.getTime(); } /** * 获得所在月份的最后一天 * @param 当前月份所在的时间 * @return 月份的最后一天 */ public static Date getLastDateByMonth(Date date) { Calendar now = Calendar.getInstance(); now.setTime(date); now.set(Calendar.MONTH, now.get(Calendar.MONTH) + 1); now.set(Calendar.DATE, 1); now.set(Calendar.DATE, now.get(Calendar.DATE) - 1); now.set(Calendar.HOUR, 11); now.set(Calendar.MINUTE, 59); now.set(Calendar.SECOND, 59); return now.getTime(); } /** * 获得所在月份的第一天 * @param 当前月份所在的时间 * @return 月份的第一天 */ public static Date getFirstDateByMonth(Date date) { Calendar now = Calendar.getInstance(); now.setTime(date); now.set(Calendar.DATE, 0); now.set(Calendar.HOUR, 12); now.set(Calendar.MINUTE, 0); now.set(Calendar.SECOND, 0); return now.getTime(); } }
package com.hexiang.utils; /** * @(#)DateUtil.java * * * @author kidd * @version 1.00 2007/8/8 */ import java.util.*; import java.text.*; import java.sql.Timestamp; public class DateUtils { /** * 时间范围:年 */ public static final int YEAR = 1; /** * 时间范围:季度 */ public static final int QUARTER = 2; /** * 时间范围:月 */ public static final int MONTH = 3; /** * 时间范围:旬 */ public static final int TENDAYS = 4; /** * 时间范围:周 */ public static final int WEEK = 5; /** * 时间范围:日 */ public static final int DAY = 6; /* 基准时间 */ private Date fiducialDate = null; private Calendar cal = null; private DateUtils(Date fiducialDate) { if (fiducialDate != null) { this.fiducialDate = fiducialDate; } else { this.fiducialDate = new Date(System.currentTimeMillis()); } this.cal = Calendar.getInstance(); this.cal.setTime(this.fiducialDate); this.cal.set(Calendar.HOUR_OF_DAY, 0); this.cal.set(Calendar.MINUTE, 0); this.cal.set(Calendar.SECOND, 0); this.cal.set(Calendar.MILLISECOND, 0); this.fiducialDate = this.cal.getTime(); } /** * 获取DateHelper实例 * * @param fiducialDate * 基准时间 * @return Date */ public static DateUtils getInstance(Date fiducialDate) { return new DateUtils(fiducialDate); } /** * 获取DateHelper实例, 使用当前时间作为基准时间 * * @return Date */ public static DateUtils getInstance() { return new DateUtils(null); } /** * 获取年的第一天 * * @param offset * 偏移量 * @return Date */ public Date getFirstDayOfYear(int offset) { cal.setTime(this.fiducialDate); cal.set(Calendar.YEAR, cal.get(Calendar.YEAR) + offset); cal.set(Calendar.MONTH, Calendar.JANUARY); cal.set(Calendar.DAY_OF_MONTH, 1); return cal.getTime(); } /** * 获取年的最后一天 * * @param offset * 偏移量 * @return Date */ public Date getLastDayOfYear(int offset) { cal.setTime(this.fiducialDate); cal.set(Calendar.YEAR, cal.get(Calendar.YEAR) + offset); cal.set(Calendar.MONTH, Calendar.DECEMBER); cal.set(Calendar.DAY_OF_MONTH, 31); return cal.getTime(); } /** * 获取季度的第一天 * * @param offset * 偏移量 * @return Date */ public Date getFirstDayOfQuarter(int offset) { cal.setTime(this.fiducialDate); cal.add(Calendar.MONTH, offset * 3); int mon = cal.get(Calendar.MONTH); if (mon >= Calendar.JANUARY && mon = Calendar.APRIL && mon = Calendar.JULY && mon = Calendar.OCTOBER && mon = Calendar.JANUARY && mon = Calendar.APRIL && mon = Calendar.JULY && mon = Calendar.OCTOBER && mon = 21) { day = 21; } else if (day >= 11) { day = 11; } else { day = 1; } if (offset > 0) { day = day + 10 * offset; int monOffset = day / 30; day = day % 30; cal.add(Calendar.MONTH, monOffset); cal.set(Calendar.DAY_OF_MONTH, day); } else { int monOffset = 10 * offset / 30; int dayOffset = 10 * offset % 30; if ((day + dayOffset) > 0) { day = day + dayOffset; } else { monOffset = monOffset - 1; day = day - dayOffset - 10; } cal.add(Calendar.MONTH, monOffset); cal.set(Calendar.DAY_OF_MONTH, day); } return cal.getTime(); } /** * 获取旬的最后一天 * * @param offset * 偏移量 * @return Date */ public Date getLastDayOfTendays(int offset) { Date date = getFirstDayOfTendays(offset + 1); cal.setTime(date); cal.add(Calendar.DAY_OF_MONTH, -1); return cal.getTime(); } /** * 获取周的第一天(MONDAY) * * @param offset * 偏移量 * @return Date */ public Date getFirstDayOfWeek(int offset) { cal.setTime(this.fiducialDate); cal.add(Calendar.DAY_OF_MONTH, offset * 7); cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); return cal.getTime(); } /** * 获取周的最后一天(SUNDAY) * * @param offset * 偏移量 * @return Date */ public Date getLastDayOfWeek(int offset) { cal.setTime(this.fiducialDate); cal.add(Calendar.DAY_OF_MONTH, offset * 7); cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); cal.add(Calendar.DAY_OF_MONTH, 6); return cal.getTime(); } /** * 获取指定时间范围的第一天 * * @param dateRangeType * 时间范围类型 * @param offset * 偏移量 * @return Date */ public Date getFirstDate(int dateRangeType, int offset) { return null; } /** * 获取指定时间范围的最后一天 * * @param dateRangeType * 时间范围类型 * @param offset * 偏移量 * @return Date */ public Date getLastDate(int dateRangeType, int offset) { return null; } /** * 根据日历的规则,为基准时间添加指定日历字段的时间量 * * @param field * 日历字段, 使用Calendar类定义的日历字段常量 * @param offset * 偏移量 * @return Date */ public Date add(int field, int offset) { cal.setTime(this.fiducialDate); cal.add(field, offset); return cal.getTime(); } /** * 根据日历的规则,为基准时间添加指定日历字段的单个时间单元 * * @param field * 日历字段, 使用Calendar类定义的日历字段常量 * @param up * 指定日历字段的值的滚动方向。true:向上滚动 / false:向下滚动 * @return Date */ public Date roll(int field, boolean up) { cal.setTime(this.fiducialDate); cal.roll(field, up); return cal.getTime(); } /** * 把字符串转换为日期 * * @param dateStr * 日期字符串 * @param format * 日期格式 * @return Date */ public static Date strToDate(String dateStr, String format) { Date date = null; if (dateStr != null && (!dateStr.equals(""))) { DateFormat df = new SimpleDateFormat(format); try { date = df.parse(dateStr); } catch (ParseException e) { e.printStackTrace(); } } return date; } /** * 把字符串转换为日期日期的格式为yyyy-MM-dd HH:ss * * @param dateStr * 日期字符串 * @return Date */ public static Date strToDate(String dateStr) { Date date = null; if (dateStr != null && (!dateStr.equals(""))) { if (dateStr.matches("\\d{4}-\\d{1,2}-\\d{1,2}")) { dateStr = dateStr + " 00:00"; } else if (dateStr.matches("\\d{4}-\\d{1,2}-\\d{1,2} \\d{1,2}")) { dateStr = dateStr + ":00"; } else { System.out.println(dateStr + " 格式不正确"); return null; } DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:ss"); try { date = df.parse(dateStr); } catch (ParseException e) { e.printStackTrace(); } } return date; } /** * 把日期转换为字符串 * * @param date * 日期实例 * @param format * 日期格式 * @return Date */ public static String dateToStr(Date date, String format) { return (date == null) ? "" : new SimpleDateFormat(format).format(date); } public static String dateToStr(Date date) { return (date == null) ? "" : new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(date); } /** * 取得当前日期 年-月-日 * * @return Date */ public static String getCurrentDate() { DateFormat f = new SimpleDateFormat("yyyy-MM-dd"); return f.format(Calendar.getInstance().getTime()); } public static void main(String[] args) { DateUtils dateHelper = DateUtils.getInstance(); /* Year */ for (int i = -5; i <= 5; i++) { System.out.println("FirstDayOfYear(" + i + ") = " + dateHelper.getFirstDayOfYear(i)); System.out.println("LastDayOfYear(" + i + ") = " + dateHelper.getLastDayOfYear(i)); } /* Quarter */ for (int i = -5; i <= 5; i++) { System.out.println("FirstDayOfQuarter(" + i + ") = " + dateHelper.getFirstDayOfQuarter(i)); System.out.println("LastDayOfQuarter(" + i + ") = " + dateHelper.getLastDayOfQuarter(i)); } /* Month */ for (int i = -5; i <= 5; i++) { System.out.println("FirstDayOfMonth(" + i + ") = " + dateHelper.getFirstDayOfMonth(i)); System.out.println("LastDayOfMonth(" + i + ") = " + dateHelper.getLastDayOfMonth(i)); } /* Week */ for (int i = -5; i <= 5; i++) { System.out.println("FirstDayOfWeek(" + i + ") = " + dateHelper.getFirstDayOfWeek(i)); System.out.println("LastDayOfWeek(" + i + ") = " + dateHelper.getLastDayOfWeek(i)); } /* Tendays */ for (int i = -5; i <= 5; i++) { System.out.println("FirstDayOfTendays(" + i + ") = " + dateHelper.getFirstDayOfTendays(i)); System.out.println("LastDayOfTendays(" + i + ") = " + dateHelper.getLastDayOfTendays(i)); } } /** * 取当前日期的字符串形式,"XXXX年XX月XX日" * * @return java.lang.String */ public static String getPrintDate() { String printDate = ""; Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); printDate += calendar.get(Calendar.YEAR) + "年"; printDate += (calendar.get(Calendar.MONTH) + 1) + "月"; printDate += calendar.get(Calendar.DATE) + "日"; return printDate; } /** * 将指定的日期字符串转化为日期对象 * * @param dateStr * 日期字符串 * @return java.util.Date */ public static Date getDate(String dateStr, String format) { if (dateStr == null) { return new Date(); } if (format == null) { format = "yyyy-MM-dd"; } SimpleDateFormat sdf = new SimpleDateFormat(format); try { Date date = sdf.parse(dateStr); return date; } catch (Exception e) { return null; } } /** * 从指定Timestamp中得到相应的日期的字符串形式 日期"XXXX-XX-XX" * * @param dateTime * @return 、String */ public static String getDateFromDateTime(Timestamp dateTime) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); return sdf.format(dateTime).toString(); } /** * 得到当前时间 return java.sql.Timestamp * * @return Timestamp */ public static Timestamp getNowTimestamp() { long curTime = System.currentTimeMillis(); return new Timestamp(curTime); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值