Java 日期工具类(自用)

Java 日期工具类(自用)

拥有的功能

  • 字符串转日期
  • 日期转字符串
  • 获取当前日所在的周一是几号
  • 当前日期周的最后一天
  • 根据日期区间获取月份列表
  • 根据日期获取年度中的周索引
  • 根据年份获取年中周列表
  • 获取某年的第几周的开始日期
  • 获取某年的第几周的结束日期
  • 获取当前时间所在周的开始日期
  • 获取当前时间所在周的结束日期
  • 获得上周一的日期
  • 获得本周一的日期
  • 获得下周一的日期
  • 获得今天日期
  • 获得本月一日的日期
/**
 * 日期操作工具类
 */
public class DateUtils {
    /**
     * 日期转换-  String -> Date
     *
     * @param dateString 字符串时间
     * @return Date类型信息
     * @throws Exception 抛出异常
     */
    public static Date parseString2Date(String dateString) throws Exception {
        if (dateString == null) {
            return null;
        }
        return parseString2Date(dateString, "yyyy-MM-dd");
    }

    /**
     * 日期转换-  String -> Date
     *
     * @param dateString 字符串时间
     * @param pattern    格式模板
     * @return Date类型信息
     * @throws Exception 抛出异常
     */
    public static Date parseString2Date(String dateString, String pattern) throws Exception {
        if (dateString == null) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        Date date = sdf.parse(dateString);
        return date;
    }

    /**
     * 日期转换 Date -> String
     *
     * @param date Date类型信息
     * @return 字符串时间
     * @throws Exception 抛出异常
     */
    public static String parseDate2String(Date date) throws Exception {
        if (date == null) {
            return null;
        }
        return parseDate2String(date, "yyyy-MM-dd");
    }

    /**
     * 日期转换 Date -> String
     *
     * @param date    Date类型信息
     * @param pattern 格式模板
     * @return 字符串时间
     * @throws Exception 抛出异常
     */
    public static String parseDate2String(Date date, String pattern) throws Exception {
        if (date == null) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        String strDate = sdf.format(date);
        return strDate;
    }

    /**
     * 获取当前日期的本周一是几号
     *
     * @return 本周一的日期
     */
    public static Date getThisWeekMonday() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        // 获得当前日期是一个星期的第几天
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
        if (1 == dayWeek) {
            cal.add(Calendar.DAY_OF_MONTH, -1);
        }
        // 设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        // 获得当前日期是一个星期的第几天
        int day = cal.get(Calendar.DAY_OF_WEEK);
        // 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值
        cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);
        return cal.getTime();
    }

    /**
     * 获取当前日期周的最后一天
     *
     * @return 当前日期周的最后一天
     */
    public static Date getSundayOfThisWeek() {
        Calendar c = Calendar.getInstance();
        int dayOfWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
        if (dayOfWeek == 0) {
            dayOfWeek = 7;
        }
        c.add(Calendar.DATE, -dayOfWeek + 7);
        return c.getTime();
    }

    /**
     * 根据日期区间获取月份列表
     *
     * @param minDate 开始时间
     * @param maxDate 结束时间
     * @return 月份列表
     * @throws Exception
     */
    public static List<String> getMonthBetween(String minDate, String maxDate, String format) throws Exception {
        ArrayList<String> result = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

        Calendar min = Calendar.getInstance();
        Calendar max = Calendar.getInstance();

        min.setTime(sdf.parse(minDate));
        min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);

        max.setTime(sdf.parse(maxDate));
        max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);
        SimpleDateFormat sdf2 = new SimpleDateFormat(format);

        Calendar curr = min;
        while (curr.before(max)) {
            result.add(sdf2.format(curr.getTime()));
            curr.add(Calendar.MONTH, 1);
        }

        return result;
    }

    /**
     * 根据日期获取年度中的周索引
     *
     * @param date 日期
     * @return 周索引
     * @throws Exception
     */
    public static Integer getWeekOfYear(String date) throws Exception {
        Date useDate = parseString2Date(date);
        Calendar cal = Calendar.getInstance();
        cal.setTime(useDate);
        return cal.get(Calendar.WEEK_OF_YEAR);
    }

    /**
     * 根据年份获取年中周列表
     *
     * @param year 年分
     * @return 周列表
     * @throws Exception
     */
    public static Map<Integer, String> getWeeksOfYear(String year) throws Exception {
        Date useDate = parseString2Date(year, "yyyy");
        Calendar cal = Calendar.getInstance();
        cal.setTime(useDate);
        //获取年中周数量
        int weeksCount = cal.getWeeksInWeekYear();
        Map<Integer, String> mapWeeks = new HashMap<>(55);
        for (int i = 0; i < weeksCount; i++) {
            cal.get(Calendar.DAY_OF_YEAR);
            mapWeeks.put(i + 1, parseDate2String(getFirstDayOfWeek(cal.get(Calendar.YEAR), i)));
        }
        return mapWeeks;
    }

    /**
     * 获取某年的第几周的开始日期
     *
     * @param year 年分
     * @param week 周索引
     * @return 开始日期
     * @throws Exception
     */
    public static Date getFirstDayOfWeek(int year, int week) throws Exception {
        Calendar c = new GregorianCalendar();
        c.set(Calendar.YEAR, year);
        c.set(Calendar.MONTH, Calendar.JANUARY);
        c.set(Calendar.DATE, 1);

        Calendar cal = (GregorianCalendar) c.clone();
        cal.add(Calendar.DATE, week * 7);

        return getFirstDayOfWeek(cal.getTime());
    }

    /**
     * 获取某年的第几周的结束日期
     *
     * @param year 年份
     * @param week 周索引
     * @return 结束日期
     * @throws Exception
     */
    public static Date getLastDayOfWeek(int year, int week) throws Exception {
        Calendar c = new GregorianCalendar();
        c.set(Calendar.YEAR, year);
        c.set(Calendar.MONTH, Calendar.JANUARY);
        c.set(Calendar.DATE, 1);

        Calendar cal = (GregorianCalendar) c.clone();
        cal.add(Calendar.DATE, week * 7);

        return getLastDayOfWeek(cal.getTime());
    }

    /**
     * 获取当前时间所在周的开始日期
     *
     * @param date 当前时间
     * @return 开始时间
     */
    public static Date getFirstDayOfWeek(Date date) {
        Calendar c = new GregorianCalendar();
        c.setFirstDayOfWeek(Calendar.SUNDAY);
        c.setTime(date);
        c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek());
        return c.getTime();
    }

    /**
     * 获取当前时间所在周的结束日期
     *
     * @param date 当前时间
     * @return 结束日期
     */
    public static Date getLastDayOfWeek(Date date) {
        Calendar c = new GregorianCalendar();
        c.setFirstDayOfWeek(Calendar.SUNDAY);
        c.setTime(date);
        c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() + 6);
        return c.getTime();
    }
    //获得上周一的日期
    public static Date geLastWeekMonday(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(getThisWeekMonday(date));
        cal.add(Calendar.DATE, -7);
        return cal.getTime();
    }

    //获得本周一的日期
    public static Date getThisWeekMonday(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        // 获得当前日期是一个星期的第几天
        int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
        if (1 == dayWeek) {
            cal.add(Calendar.DAY_OF_MONTH, -1);
        }
        // 设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        // 获得当前日期是一个星期的第几天
        int day = cal.get(Calendar.DAY_OF_WEEK);
        // 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值
        cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);
        return cal.getTime();
    }

    //获得下周一的日期
    public static Date getNextWeekMonday(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(getThisWeekMonday(date));
        cal.add(Calendar.DATE, 7);
        return cal.getTime();
    }

    //获得今天日期
    public static Date getToday(){
        return new Date();
    }

    //获得本月一日的日期
    public static Date getFirstDay4ThisMonth(){
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH,1);
        return calendar.getTime();
    }

    public static void main(String[] args) {
        try {
            System.out.println("本周一" + parseDate2String(getThisWeekMonday()));
            System.out.println("本月一日" + parseDate2String(getFirstDay4ThisMonth()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
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、付费专栏及课程。

余额充值