使用DateUtil工具类偏移日期

使用DateUtil工具类偏移日期


一、依赖

        <!--工具依赖-->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.16</version>
        </dependency>

二、源码

部分代码

	// --------------------------------------------------- Offset for now

	/**
	 * 昨天
	 *
	 * @return 昨天
	 */
	public static DateTime yesterday() {
		return offsetDay(new DateTime(), -1);
	}

	/**
	 * 明天
	 *
	 * @return 明天
	 * @since 3.0.1
	 */
	public static DateTime tomorrow() {
		return offsetDay(new DateTime(), 1);
	}

	/**
	 * 上周
	 *
	 * @return 上周
	 */
	public static DateTime lastWeek() {
		return offsetWeek(new DateTime(), -1);
	}

	/**
	 * 下周
	 *
	 * @return 下周
	 * @since 3.0.1
	 */
	public static DateTime nextWeek() {
		return offsetWeek(new DateTime(), 1);
	}

	/**
	 * 上个月
	 *
	 * @return 上个月
	 */
	public static DateTime lastMonth() {
		return offsetMonth(new DateTime(), -1);
	}

	/**
	 * 下个月
	 *
	 * @return 下个月
	 * @since 3.0.1
	 */
	public static DateTime nextMonth() {
		return offsetMonth(new DateTime(), 1);
	}

	/**
	 * 偏移毫秒数
	 *
	 * @param date   日期
	 * @param offset 偏移毫秒数,正数向未来偏移,负数向历史偏移
	 * @return 偏移后的日期
	 */
	public static DateTime offsetMillisecond(Date date, int offset) {
		return offset(date, DateField.MILLISECOND, offset);
	}

	/**
	 * 偏移秒数
	 *
	 * @param date   日期
	 * @param offset 偏移秒数,正数向未来偏移,负数向历史偏移
	 * @return 偏移后的日期
	 */
	public static DateTime offsetSecond(Date date, int offset) {
		return offset(date, DateField.SECOND, offset);
	}

	/**
	 * 偏移分钟
	 *
	 * @param date   日期
	 * @param offset 偏移分钟数,正数向未来偏移,负数向历史偏移
	 * @return 偏移后的日期
	 */
	public static DateTime offsetMinute(Date date, int offset) {
		return offset(date, DateField.MINUTE, offset);
	}

	/**
	 * 偏移小时
	 *
	 * @param date   日期
	 * @param offset 偏移小时数,正数向未来偏移,负数向历史偏移
	 * @return 偏移后的日期
	 */
	public static DateTime offsetHour(Date date, int offset) {
		return offset(date, DateField.HOUR_OF_DAY, offset);
	}

	/**w
	 * 偏移天
	 *
	 * @param date   日期
	 * @param offset 偏移天数,正数向未来偏移,负数向历史偏移
	 * @return 偏移后的日期
	 */
	public static DateTime offsetDay(Date date, int offset) {
		return offset(date, DateField.DAY_OF_YEAR, offset);
	}

	/**
	 * 偏移周
	 *
	 * @param date   日期
	 * @param offset 偏移周数,正数向未来偏移,负数向历史偏移
	 * @return 偏移后的日期
	 */
	public static DateTime offsetWeek(Date date, int offset) {
		return offset(date, DateField.WEEK_OF_YEAR, offset);
	}

	/**
	 * 偏移月
	 *
	 * @param date   日期
	 * @param offset 偏移月数,正数向未来偏移,负数向历史偏移
	 * @return 偏移后的日期
	 */
	public static DateTime offsetMonth(Date date, int offset) {
		return offset(date, DateField.MONTH, offset);
	}

	/**
	 * 获取指定日期偏移指定时间后的时间,生成的偏移日期不影响原日期
	 *
	 * @param date      基准日期
	 * @param dateField 偏移的粒度大小(小时、天、月等){@link DateField}
	 * @param offset    偏移量,正数为向后偏移,负数为向前偏移
	 * @return 偏移后的日期
	 */
	public static DateTime offset(Date date, DateField dateField, int offset) {
		return dateNew(date).offset(dateField, offset);
	}
	// ------------------------------------ Offset end ----------------------------------------------

部分代码


/**
 * 日期各个部分的枚举<br>
 * 与Calendar相应值对应
 *
 * @author Looly
 *
 */
public enum DateField {

	/**
	 * 世纪
	 *
	 * @see Calendar#ERA
	 */
	ERA(Calendar.ERA),
	/**
	 * 年
	 *
	 * @see Calendar#YEAR
	 */
	YEAR(Calendar.YEAR),
	/**
	 * 月
	 *
	 * @see Calendar#MONTH
	 */
	MONTH(Calendar.MONTH),
	/**
	 * 一年中第几周
	 *
	 * @see Calendar#WEEK_OF_YEAR
	 */
	WEEK_OF_YEAR(Calendar.WEEK_OF_YEAR),
	/**
	 * 一月中第几周
	 *
	 * @see Calendar#WEEK_OF_MONTH
	 */
	WEEK_OF_MONTH(Calendar.WEEK_OF_MONTH),
	/**
	 * 一月中的第几天
	 *
	 * @see Calendar#DAY_OF_MONTH
	 */
	DAY_OF_MONTH(Calendar.DAY_OF_MONTH),
	/**
	 * 一年中的第几天
	 *
	 * @see Calendar#DAY_OF_YEAR
	 */
	DAY_OF_YEAR(Calendar.DAY_OF_YEAR),
	/**
	 * 周几,1表示周日,2表示周一
	 *
	 * @see Calendar#DAY_OF_WEEK
	 */
	DAY_OF_WEEK(Calendar.DAY_OF_WEEK),
	/**
	 * 天所在的周是这个月的第几周
	 *
	 * @see Calendar#DAY_OF_WEEK_IN_MONTH
	 */
	DAY_OF_WEEK_IN_MONTH(Calendar.DAY_OF_WEEK_IN_MONTH),
	/**
	 * 上午或者下午
	 *
	 * @see Calendar#AM_PM
	 */
	AM_PM(Calendar.AM_PM),
	/**
	 * 小时,用于12小时制
	 *
	 * @see Calendar#HOUR
	 */
	HOUR(Calendar.HOUR),
	/**
	 * 小时,用于24小时制
	 *
	 * @see Calendar#HOUR
	 */
	HOUR_OF_DAY(Calendar.HOUR_OF_DAY),
	/**
	 * 分钟
	 *
	 * @see Calendar#MINUTE
	 */
	MINUTE(Calendar.MINUTE),
	/**
	 * 秒
	 *
	 * @see Calendar#SECOND
	 */
	SECOND(Calendar.SECOND),
	/**
	 * 毫秒
	 *
	 * @see Calendar#MILLISECOND
	 */
	MILLISECOND(Calendar.MILLISECOND);

	// ---------------------------------------------------------------
}

三、示例代码

    @Test
    void test() {
        //获取当前时间(默认yyyy-MM-dd HH:mm:ss格式)
        log.info(DateUtil.now());//当前时间
        log.info(DateUtil.yesterday().toString());//获取昨天
        log.info(DateUtil.offsetDay(DateUtil.date().toJdkDate(),1).toString());//获取一天后
        log.info(DateUtil.offsetMonth(DateUtil.date().toJdkDate(),1).toString());//获取一个月后
        log.info(DateUtil.offset(new Date(),DateField.YEAR,10).toString());//当前时间增加十年
    }

在这里插入图片描述

  • 无畏风雨,才见彩虹;不怕跌倒,才懂成长。坚信自己,勇敢向前,未来属于你。
  • 拥有梦想是勇气的表现,实现梦想是行动的结果。只有持之以恒,才能创造奇迹。
  • 生活或许会给你磨难,但坚强的人能把压力转化为动力,逆境中才能绽放出真正的力量。
  • 成功不是偶然,而是每天坚定的信念和不懈的努力累积而成。保持热情,迎接挑战,胜利必将属于你。
  • 坚持的力量,超越想象的可能。走出舒适区,追随内心的声音,并永不放弃追寻自己的梦想。
  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 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
发出的红包

打赏作者

和烨

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值