时间工具类DateUtils

时间工具类DateUtils

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Date;

/**
 * @Description : 日期工具类
 * @Author : aqrlmy
 */
public class DateUtils {
    private static final Logger logger = LoggerFactory.getLogger(DateUtils.class);
    private static final String PATTERN_YMD = "yyyy-MM-dd";
    private static final String PATTERN_YMD_HMS = "yyyy-MM-dd HH:mm:ss";

    /**
     * 日期转字符串,自定义格式
     *
     * @param date    日期
     * @param pattern 转换的格式
     * @return 转换后的字符串
     */
    public static String parseDate(Date date, String pattern) {
        if (date == null) {
            return "";
        }
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        return format.format(date);
    }
    
    //日期转字符串,固定格式
    public static String parseDate(Date date) {
        if (date == null) {
            return "";
        }
        SimpleDateFormat format = new SimpleDateFormat(PATTERN_YMD);
        return format.format(date);
    }

    //日期转字符串,固定格式
    public static String parseDate(Date date, Integer type) {
        if (date == null) {
            return "";
        }
        SimpleDateFormat format = new SimpleDateFormat(PATTERN_YMD_HMS);
        return format.format(date);
    }
    
    //字符串转日期,固定格式
    public static Date stringToDate(String date) {
        SimpleDateFormat format = new SimpleDateFormat(PATTERN_YMD);
        try {
            return format.parse(date);
        } catch (Exception e) {
            logger.error("日期解析异常,参数: {}", date);
        }
        return null;
    }

    //字符串转日期,固定格式
    public static Date stringToDate(String date, Integer type) {
        SimpleDateFormat format = new SimpleDateFormat(PATTERN_YMD_HMS);
        try {
            return format.parse(date);
        } catch (Exception e) {
            logger.error("日期解析异常,参数: {}", date);
        }
        return null;
    }

    /**
     * 计算两个日期之间的绝对天数差。
     * @param startTime 起始日期
     * @param endTime 结束日期
     * @return 两个日期之间相差的天数(结果为正数,表示结束日期在起始日期之后;结果为负数时返回其绝对值)
     */
    public static long calculateDays(String startTime, String endTime) {
        // 创建一个日期时间格式器,根据提供的格式字符串
        DateTimeFormatter formatterLocalTime = DateTimeFormatter.ofPattern(PATTERN_YMD);
        LocalDate localStartDate = LocalDate.parse(startTime, formatterLocalTime);
        LocalDate localEndDate = LocalDate.parse(endTime, formatterLocalTime);

        return Math.abs(localStartDate.until(localEndDate, ChronoUnit.DAYS));
    }
    
    /**
     * 计算两个日期之间的绝对天数差。
     * @param startTime 起始日期
     * @param endTime 结束日期
     * @return 两个日期之间相差的天数(结果为正数,表示结束日期在起始日期之后;结果为负数时返回其绝对值)
     */
    public static long calculateDays(String startTime, String endTime,Integer type) {
        // 创建一个日期时间格式器,根据提供的格式字符串
        DateTimeFormatter formatterLocalTime = DateTimeFormatter.ofPattern(PATTERN_YMD_HMS);
        LocalDate localStartDate = LocalDate.parse(startTime, formatterLocalTime);
        LocalDate localEndDate = LocalDate.parse(endTime, formatterLocalTime);

        return Math.abs(localStartDate.until(localEndDate, ChronoUnit.DAYS));
    }


    /**
     * 将日期字符串转换为当天的具有时分秒的最早时间对象
     * @param inputDateString 日期字符串
     * @return 当前日期的最早时间对象
     */
    public static String getStartDate(String inputDateString) {
        // 将输入的字符串按照"yyyy-MM-dd"格式解析为LocalDate对象
        LocalDate localDate = LocalDate.parse(inputDateString, DateTimeFormatter.ofPattern(PATTERN_YMD_HMS));

        // 将得到的LocalDate对象与默认的时间(00:00:00)组合成LocalDateTime对象
        LocalDateTime localDateTime = localDate.atStartOfDay();
        return  localDateTime.format(DateTimeFormatter.ofPattern(PATTERN_YMD_HMS));
    }

    /**
     * 将日期字符串转换为当天的具有时分秒的最晚时间对象
     * @param inputDateString 日期字符串
     * @return 当前日期的最晚时间对象
     */
    public static String getEndDate(String inputDateString) {
        LocalDate localDate = LocalDate.parse(inputDateString, DateTimeFormatter.ofPattern(PATTERN_YMD_HMS));

        // 结合一天的最晚时间
        LocalDateTime localDateTime = localDate.atTime(LocalTime.MAX);

        // 转换成字符串格式并返回
        return  localDateTime.format(DateTimeFormatter.ofPattern(PATTERN_YMD_HMS));
    }

    /**
     * 将日期转换为当天的具有时分秒的最早时间对象
     * @param time 日期
     * @return 当前日期的最早时间对象
     */
    public static Date getStartDate(Date time) {
        if (time == null) {
            return null;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(time);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    /**
     * 将日期转换为当天的具有时分秒的最晚时间对象
     * @param time 日期
     * @return 当前日期的最晚时间对象
     */
    public static Date getEndDate(Date time) {
        if (time == null) {
            return null;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(time);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        return calendar.getTime();
    }

    /**
     * 获取指定日期月份的开始时间
     *
     * @param time
     * @return
     */
    public static Date getStartOfMonth(Date time) {
        if (time == null) {
            return null;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(time);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    /**
     * 获取指定日期月份的结束时间
     *
     * @param time
     * @return
     */
    public static Date getEndOfMonth(Date time) {
        if (time == null) {
            return null;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(time);
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        return calendar.getTime();
    }

    /**
     * 计算两个日期之间的绝对年数差。
     * @param startTime 起始日期
     * @param endTime 结束日期
     * @return 两个日期之间相差的年数(结果为正数,表示结束日期在起始日期之后;结果为负数时返回其绝对值)
     */
    public static long calculateYears(String startTime, String endTime) {
        // 创建一个日期时间格式器,根据提供的格式字符串
        DateTimeFormatter formatterLocalTime = DateTimeFormatter.ofPattern(PATTERN_YMD);
        LocalDate localStartDate = LocalDate.parse(startTime, formatterLocalTime);
        LocalDate localEndDate = LocalDate.parse(endTime, formatterLocalTime);

        return Math.abs(localStartDate.until(localEndDate, ChronoUnit.YEARS));
    }

    /**
     * 计算两个日期之间的绝对年数差。
     * @param startTime 起始日期
     * @param endTime 结束日期
     * @return 两个日期之间相差的年数(结果为正数,表示结束日期在起始日期之后;结果为负数时返回其绝对值)
     */
    public static long calculateYears(String startTime, String endTime,Integer type) {
        // 创建一个日期时间格式器,根据提供的格式字符串
        DateTimeFormatter formatterLocalTime = DateTimeFormatter.ofPattern(PATTERN_YMD_HMS);
        LocalDate localStartDate = LocalDate.parse(startTime, formatterLocalTime);
        LocalDate localEndDate = LocalDate.parse(endTime, formatterLocalTime);

        return Math.abs(localStartDate.until(localEndDate, ChronoUnit.YEARS));
    }

    /**
     * 计算两个日期之间的绝对月数差。
     * @param startTime 起始日期
     * @param endTime 结束日期
     * @return 两个日期之间相差的月数(结果为正数,表示结束日期在起始日期之后;结果为负数时返回其绝对值)
     */
    public static long calculateMonths(String startTime, String endTime) {
        // 创建一个日期时间格式器,根据提供的格式字符串
        DateTimeFormatter formatterLocalTime = DateTimeFormatter.ofPattern(PATTERN_YMD);
        LocalDate localStartDate = LocalDate.parse(startTime, formatterLocalTime);
        LocalDate localEndDate = LocalDate.parse(endTime, formatterLocalTime);

        return Math.abs(localStartDate.until(localEndDate, ChronoUnit.MONTHS));
    }

    /**
     * 计算两个日期之间的绝对小时差。
     * @param startTime 起始日期
     * @param endTime 结束日期
     * @return 两个日期之间相差的小时数(结果为正数,表示结束日期在起始日期之后;结果为负数时返回其绝对值)
     */
    public static long calculateHours(String startTime, String endTime) {
        // 创建一个日期时间格式器,根据提供的格式字符串
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(PATTERN_YMD_HMS);
        LocalDateTime localStartDate = LocalDateTime.parse(startTime, formatter);
        LocalDateTime localEndDate = LocalDateTime.parse(endTime, formatter);

        return Math.abs(localStartDate.until(localEndDate, ChronoUnit.HOURS));
    }


    /**
     * 基于开始时间 + i 天的字符串日期数据
     * @param startTime 起始日期
     * @param i 叠加天数
     * @return String类型的日期数据
     */
    public static String datePlusDay(String startTime, int i) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(PATTERN_YMD); // 修改这里为"yyyy-MM-dd"
        LocalDate localStartDate = LocalDate.parse(startTime, formatter);
        LocalDate localDateAfterAddingDays = localStartDate.plusDays(i);

        return localDateAfterAddingDays.format(DateTimeFormatter.ofPattern(PATTERN_YMD)); // 如果返回结果仅需日期部分,则保持不变
    }
    
    /**
     * 计算两个Date对象天数之差
     * @param date1 Date时间1
     * @param date1 Date时间2
     * @return int 天数
     */
     public static int differentDays(Date date1, Date date2) {
    	Calendar cal1 = Calendar.getInstance();
    	cal1.setTime(date1);
    	Calendar cal2 = Calendar.getInstance();
    	cal2.setTime(date2);
    	int day1 = cal1.get(Calendar.DAY_OF_YEAR);
    	int day2 = cal2.get(Calendar.DAY_OF_YEAR);
    	int year1 = cal1.get(Calendar.YEAR);
    	int year2 = cal2.get(Calendar.YEAR);
   		if (year1 != year2) {
        	int timeDistance = 0;
        	for (int i = year1; i < year2; i++) {
            	if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0)    //闰年
            	{
                	timeDistance += 366;
            	} else    //不是闰年
            	{
                	timeDistance += 365;
            	}
        	}
		return timeDistance + (day2 - day1);
    	} else {
        	return day2 - day1;
    	}
	}
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值