0
点赞
收藏
分享

微信扫一扫

LocalDateTime时间工具类

小禹说财 2022-03-10 阅读 119
java
package com.susu.demo.utils;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.StrUtil;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.assertj.core.util.Lists;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.time.temporal.TemporalUnit;
import java.util.Date;
import java.util.List;

/**
 * 在Java8中使用LocalDateTime时间工具类
 */
@Slf4j
@UtilityClass
public class LDTUtils {
	// 获取当前时间的LocalDateTime对象
	// LocalDateTime.now();

	// 根据年月日构建LocalDateTime
	// LocalDateTime.of();

	// 比较日期先后
	// LocalDateTime.now().isBefore(),
	// LocalDateTime.now().isAfter(),

	/**
	 * 日期格式yyyy-MM-dd
	 */
	public final static String	DATE_PATTERN		= DatePattern.NORM_DATE_PATTERN;

	/**
	 * 日期时间格式yyyy-MM-dd HH:mm:ss
	 */
	public final static String	DATE_TIME_PATTERN	= DatePattern.NORM_DATETIME_PATTERN;

	/**
	 * 日期时间格式yyyy-MM-dd HH:mm:ss.SSS
	 */
	public final static String	DATETIME_MS_PATTERN	= DatePattern.NORM_DATETIME_MS_PATTERN;

	public final static String PURE_DATE_PATTERN = DatePattern.PURE_DATE_PATTERN;

	public static final String DATE_HH_PATTERN = "yyyyMMddHH";

	public static final String DATE_DD_PATTERN = "yyyyMMdd";


	/**
	 * Date转换为LocalDateTime
	 */
	public LocalDateTime convert(Date date) {
		return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
	}

	/**
	 * LocalDateTime转换为Date
	 */
	public Date convert(LocalDateTime time) {
		return Date.from(time.atZone(ZoneId.systemDefault()).toInstant());
	}

	/**
	 * 格式化指定时间,默认格式为:yyyy-MM-dd HH:mm:ss
	 */
	public String format(LocalDateTime time) {
		return format(time, null);
	}

	/**
	 * 格式化指定时间为指定格式
	 */
	public String format(LocalDateTime time, String pattern) {
		if (StrUtil.isBlank(pattern)) {
			pattern = DATE_TIME_PATTERN;
		}
		return time.format(DateTimeFormatter.ofPattern(pattern));
	}

	/**
	 * 格式化当前时间,默认格式为:yyyy-MM-dd HH:mm:ss
	 */
	public String formatNow() {
		return formatNow(null);
	}

	/**
	 * 格式化当前时间为指定格式
	 */
	public String formatNow(String pattern) {
		return format(LocalDateTime.now(), pattern);
	}

	/**
	 * 将毫秒解析为日期
	 */
	public LocalDateTime parse(Long millis) {
		return LocalDateTime.ofInstant(Instant.ofEpochMilli(millis), ZoneId.systemDefault());
	}

	/**
	 * 将字符串解析为日期,默认格式为:yyyy-MM-dd HH:mm:ss
	 */
	public LocalDateTime parse(String str) {
		return parse(str, null);
	}

	/**
	 * 将字符串解析为日期
	 */
	public LocalDateTime parse(String str, String pattern) {
		if (StrUtil.isBlank(pattern)) {
			pattern = DATE_TIME_PATTERN;
		}
		return LocalDateTime.parse(str, DateTimeFormatter.ofPattern(pattern));
	}

	/**
	 * 将以秒为单位的时间长度,转换成 格式为 天:时:分:秒 格式
	 * @param time 时间长度[秒]
	 */
	public String transfer(int time) {
		String times = StrUtil.format("{}:{}:{}",
			String.format("%02d", (time / 3600) % 24),
			String.format("%02d", (time / 60) % 60),
			String.format("%02d", time % 60));
		String d = String.format("%04d", time / 86400);
		if (!"0000".equals(d)) {
			times = d + ":" + times;
		}
		return times;
	}

	/**
	 * 日期加上一个数,根据field不同加不同值,field为ChronoUnit
	 */
	public LocalDateTime plus(LocalDateTime time, long number, TemporalUnit field) {
		return time.plus(number, field);
	}

	/**
	 * 日期减去一个数,根据field不同减不同值,field参数为ChronoUnit
	 */
	public LocalDateTime minu(LocalDateTime time, long number, TemporalUnit field) {
		return time.minus(number, field);
	}

	/**
	 * 获取两个日期的差 field参数为ChronoUnit
	 */
	public long betweenTwoTime(LocalDateTime startTime, LocalDateTime endTime, ChronoUnit field) {
		Period period = Period.between(LocalDate.from(startTime), LocalDate.from(endTime));
		if (field == ChronoUnit.YEARS)
			return period.getYears();
		if (field == ChronoUnit.MONTHS)
			return period.getYears() * 12 + period.getMonths();
		return field.between(startTime, endTime);
	}

	/**
	 * 获取当前日期的毫秒
	 */
	public Long getMillis() {
		return getMillis(LocalDateTime.now());
	}

	/**
	 * 获取指定日期的毫秒
	 */
	public Long getMillis(LocalDateTime time) {
		return time.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
	}

	/**
	 * 获取当前日期的秒
	 */
	public Long getSeconds() {
		return getSeconds(LocalDateTime.now());
	}

	/**
	 * 获取指定日期的秒
	 */
	public Long getSeconds(LocalDateTime time) {
		return time.atZone(ZoneId.systemDefault()).toInstant().getEpochSecond();
	}

	/**
	 * 获取当天的00:00:00
	 */
	public LocalDateTime getDayStart() {
		return getDayStart(LocalDateTime.now());
	}

	/**
	 * 获取当天的23:59:59
	 */
	public LocalDateTime getDayEnd() {
		return getDayEnd(LocalDateTime.now());
	}

	/**
	 * 获取某天的00:00:00
	 */
	public LocalDateTime getDayStart(LocalDateTime time) {
		return time.with(LocalTime.MIN);
	}

	/**
	 * 获取某天的23:59:59
	 */
	public LocalDateTime getDayEnd(LocalDateTime time) {
		return time.with(LocalTime.MAX);
	}

	/**
	 * 获取本月第一天的00:00:00
	 */
	public LocalDateTime getFirstDayOfMonth() {
		return getFirstDayOfMonth(LocalDateTime.now());
	}

	/**
	 * 获取本月最后一天的23:59:59
	 */
	public LocalDateTime getLastDayOfMonth() {
		return getLastDayOfMonth(LocalDateTime.now());
	}

	/**
	 * 获取某月第一天的00:00:00
	 */
	public LocalDateTime getFirstDayOfMonth(LocalDateTime time) {
		return time.with(TemporalAdjusters.firstDayOfMonth()).with(LocalTime.MIN);
	}

	/**
	 * 获取某月最后一天的23:59:59
	 */
	public LocalDateTime getLastDayOfMonth(LocalDateTime time) {
		return time.with(TemporalAdjusters.lastDayOfMonth()).with(LocalTime.MAX);
	}

	/**
	 * 获取本年第一天的00:00:00
	 */
	public LocalDateTime getFirstDayOfYear() {
		return getFirstDayOfMonth(LocalDateTime.now());
	}

	/**
	 * 获取本年最后一天的23:59:59
	 */
	public LocalDateTime getLastDayOfYear() {
		return getLastDayOfMonth(LocalDateTime.now());
	}

	/**
	 * 获取某年第一天的00:00:00
	 */
	public LocalDateTime getFirstDayOfYear(LocalDateTime time) {
		return time.with(TemporalAdjusters.firstDayOfYear()).with(LocalTime.MIN);
	}

	/**
	 * 获取某年最后一天的23:59:59
	 */
	public LocalDateTime getLastDayOfYear(LocalDateTime time) {
		return time.with(TemporalAdjusters.lastDayOfYear()).with(LocalTime.MAX);
	}

    /**
     * 获取两个天数之间的天数集合如:2020-07-01,2020-07-03,则返回07-01,07-02,07-03
     * 一般用于统计柱形图,自动补充天数
     */
    public List<String> getoffDays(String beginTime, String endTime) {
        List<String> list = Lists.newArrayList();

        // 当前遍历时间
        LocalDateTime local = LDTUtils.parse(beginTime + " 23:59:00");
        // 循环比较用
        Long now = LDTUtils.getMillis(local);
        Long end= LDTUtils.getMillis(LDTUtils.parse(endTime + " 23:59:00"));

        // 格式化返回时间
        String format = LDTUtils.format(LDTUtils.parse(now), "MM-dd");
        list.add(format);

        while (end > now) {
                local = LDTUtils.plus(local, 1, ChronoUnit.DAYS);
                now = LDTUtils.getMillis(local);
                list.add(LDTUtils.format(LDTUtils.parse(now), "MM-dd"));
        }
        return list;
    }


	/**
	 * 根据long时间类型转换为String类型
	 */
	public String formatLongToString(Long time, String pattern) {
		try {
			if (StrUtil.isBlank(pattern)) {
				pattern = DATE_TIME_PATTERN;
			}
			LocalDateTime parse = parse(time);
			return parse.format(DateTimeFormatter.ofPattern(pattern));
		} catch (Exception e) {
			log.error("系统异常:{}",e);
		}
		return null;
	}

}
package com.susu.demo.utils;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;

import com.nuctech.common.core.exception.ServiceException;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.StrUtil;
import lombok.experimental.UtilityClass;

/**
 * 系统帮助类
 */
@UtilityClass
public class HelperUtils {

	/**
	 * 统一limit语句格式化
	 */
	public String LIMIT(int limit) {
		return StrUtil.format("limit {}", limit);
	}
	/**
	 * 检查开始、结束时间(精确到分)是否在指定时间范围内
	 * @return true-满足 false-不满足
	 */
	public boolean checkTimeRange(String startTime, String endTime, Duration duration) {
		if (StrUtil.isBlank(startTime) || StrUtil.isBlank(endTime)) {
			throw new ServiceException("开始时间、结束时间不能为空!");
		}

		LocalDateTime st = LDTUtils.parse(startTime, DatePattern.NORM_DATETIME_MINUTE_PATTERN);
		LocalDateTime et = LDTUtils.parse(endTime, DatePattern.NORM_DATETIME_MINUTE_PATTERN);
		//开始时间可以等于结束时间,这样,就是0s-59s
		if (st.compareTo(et) > 0) {
			throw new ServiceException("开始时间必须小于结束时间!");
		}

		// 比较器值,如果小于则为负,如果大于则为正,等于则为0
		int compareTo = Duration.between(st, et).compareTo(duration);
		if (compareTo>=0) {
			return false;
		}
		return true;
	}

	public int checkTimeRangeNew(String startTime, String endTime, Duration duration) {
		if (StrUtil.isBlank(startTime) || StrUtil.isBlank(endTime)) {
			throw new ServiceException("开始时间、结束时间不能为空!");
		}

		LocalDateTime st = LDTUtils.parse(startTime, DatePattern.NORM_DATETIME_MINUTE_PATTERN);
		LocalDateTime et = LDTUtils.parse(endTime, DatePattern.NORM_DATETIME_MINUTE_PATTERN);
		//开始时间可以等于结束时间,这样,就是0s-59s
		if (st.compareTo(et) > 0) {
			throw new ServiceException("开始时间必须小于结束时间!");
		}

		// 比较器值,如果小于则为负,如果大于则为正,等于则为0
		return Duration.between(st,et).compareTo(duration);
	}

	/**
	 * 检查开始、结束时间(精确到秒)是否在指定时间范围内
	 * @return true-满足 false-不满足
	 */
	public boolean checkTimeMillRange(String startTime, String endTime, Duration duration) {
		if (StrUtil.isBlank(startTime) || StrUtil.isBlank(endTime)) {
			throw new ServiceException("开始时间、结束时间不能为空!");
		}

		LocalDateTime st = LDTUtils.parse(startTime, DatePattern.NORM_DATETIME_PATTERN);
		LocalDateTime et = LDTUtils.parse(endTime, DatePattern.NORM_DATETIME_PATTERN);

		if (st.compareTo(et) >= 0) {
			throw new ServiceException("开始时间必须小于结束时间!");
		}

		// 比较器值,如果小于则为负,如果大于则为正,等于则为0
		return Duration.between(st, et).compareTo(duration) < 1;
	}
	/**
	 * 获取今天的开始、结束时间
	 * @return
	 *        数组[开始时间, 结束时间]
	 */
	public static Long[] todayTimeRange() {
		LocalDateTime now = LocalDateTime.now();
		return new Long[]{LDTUtils.getMillis(now.with(LocalTime.MIN)), LDTUtils.getMillis(now.with(LocalTime.MAX))};
	}
	/**
	 * 获取今天的开始、结束时间【截止到当前时间】
	 * @return
	 *        数组[开始时间, 结束时间]
	 */
	public static Long[] todayTimeRangeWithCurrent() {
		LocalDateTime now = LocalDateTime.now();
		return new Long[]{LDTUtils.getMillis(now.with(LocalTime.MIN)), LDTUtils.getMillis(now)};
	}
	/**
	 * 获取本月的开始、结束时间
	 * @return
	 *        数组[开始时间, 结束时间]
	 */
	public static Long[] monthTimeRange() {
		LocalDateTime now = LocalDateTime.now();
		return new Long[]{
			LDTUtils.getMillis(now
					.with(TemporalAdjusters.firstDayOfMonth())
					.with(LocalTime.MIN)),
			LDTUtils.getMillis(now
					.with(TemporalAdjusters.lastDayOfMonth())
					.with(LocalTime.MAX))
		};
	}
	/**
	 * 根据指定标志获取高峰时段的开始、结束时间
	 * @param flag
	 *        指定标志:AM-早高峰,PM-晚高峰
	 */
	public static Long[] todayHighDuring(String flag) {
		if (!("AM".equals(flag) || "PM".equals(flag))) {
			throw new ServiceException("获取高峰时段的开始、结束时间的标志必须是AM或PM!");
		}

		LocalDateTime now = LocalDateTime.now();
		if ("AM".equals(flag)) {
			return new Long[]{LDTUtils.getMillis(now.with(LocalTime.of(7, 0, 0, 0))), LDTUtils.getMillis(now.with(LocalTime.of(9, 0, 0, 0)))};
		} else {
			return new Long[]{LDTUtils.getMillis(now.with(LocalTime.of(17, 0, 0, 0))), LDTUtils.getMillis(now.with(LocalTime.of(19, 0, 0, 0)))};
		}
	}
}
举报

相关推荐

0 条评论