JAVA日期时间工具类

import cn.hutool.core.date.DateUtil;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.lang.management.ManagementFactory;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static com.bms.common.utils.StringUtils.isEmpty;

/**
 * 时间工具类
 *
 * @author cp
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
    public static final String YYYY = "yyyy";

    public static final String YYYY_MM = "yyyy-MM";

    public static final String YYYY_MM_DD = "yyyy-MM-dd";
    public static final String YYYY_MM_DD_CN = "yyyy年MM月dd日";
    public static final String YYYY_MM_DD_1 = "yyyy/MM/dd";

    public static final String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static final String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM","yyyy年MM月",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate() {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate() {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime() {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow() {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format) {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date) {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date) {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts) {
        try {
            return new SimpleDateFormat(format).parse(ts);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str) {
        if (str == null) {
            return null;
        }
        try {
            return parseDate(str.toString(), parsePatterns);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算相差天数
     */
    public static int differentDaysByMillisecond(Date date1, Date date2) {
        return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
    }

    /**
     * 计算时间差
     *
     * @param endDate   最后时间
     * @param startTime 开始时间
     * @return 时间差(天/小时/分钟)
     */
    public static String timeDistance(Date endDate, Date startTime) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - startTime.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 增加 LocalDateTime ==> Date
     */
    public static Date toDate(LocalDateTime temporalAccessor) {
        ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 增加 LocalDate ==> Date
     */
    public static Date toDate(LocalDate temporalAccessor) {
        LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 获取某年所有月份列表
     */
    public static List<String> yearMonths(String year) {
        year = isEmpty(year) ? dateTimeNow(YYYY) : year;
        int months = dateTimeNow(YYYY).equals(year) ? Integer.parseInt(DateFormatUtils.format(new Date(), "M")) : 12;
        List<String> list = new ArrayList<>();
        for (int i = 1; i <= months; i++) {
            String month = year + "-" + (i < 10 ? "0" + i : i);
            list.add(month);
        }
        return list;
    }

    /**
     * 计算两个日期相差月数<br>
     * 在非重置情况下,如果起始日期的天大于结束日期的天,月数要少算1(不足1个月)
     *
     * @param begin   起始日期
     * @param end     结束日期
     * @param isReset 是否重置时间为起始时间(重置天时分秒)
     * @return 相差月数
     * @since 3.0.8
     */
    public static long betweenMonth(Date begin, Date end, boolean isReset) {
        Date beginDate = begin;
        Date endDate = end;
        if (begin.getTime() >  end.getTime()){
            endDate = begin;
            beginDate = end;
        }
        final Calendar beginCal = DateUtil.calendar(beginDate);
        final Calendar endCal = DateUtil.calendar(endDate);

        final int betweenYear = endCal.get(Calendar.YEAR) - beginCal.get(Calendar.YEAR);
        final int betweenMonthOfYear = endCal.get(Calendar.MONTH) - beginCal.get(Calendar.MONTH);

        int result = betweenYear * 12 + betweenMonthOfYear;
        if (!isReset) {
            endCal.set(Calendar.YEAR, beginCal.get(Calendar.YEAR));
            endCal.set(Calendar.MONTH, beginCal.get(Calendar.MONTH));
            long between = endCal.getTimeInMillis() - beginCal.getTimeInMillis();
            if (between < 0) {
                return result - 1;
            }
        }
        return result;
    }

    /**
     * 判断当前时间是否在[startTime, endTime]区间,注意时间格式要一致
     *
     * @param timeStr 时间段字符串(01:00~06:00),过个中间以“;”隔开
     * @return
     */
    public static boolean isEffectiveDate(String timeStr) {
        if (isEmpty(timeStr)) {
            return false;
        }
        boolean b = false;
        String checkStr = parseDateToStr("HH:mm", new Date());
        try {
            timeStr = timeStr.replaceAll(";", ";").replaceAll(":", ":");
            String timeArr[] = timeStr.split(";");
            for (String times : timeArr) {
                String[] arr = times.split("~");
                LocalTime startTime = LocalTime.parse(arr[0]);
                LocalTime endTime = LocalTime.parse(arr[1]);
                LocalTime checkTime = LocalTime.parse(checkStr);

                if (!checkTime.isBefore(startTime) && checkTime.isBefore(endTime)) {
                    System.out.println(checkStr + " 在" + arr[0] + "到" + arr[1] + "之间");
                } else {
                    System.out.println(checkStr + " 在" + arr[0] + "到" + arr[1] + "之间");
                    b = true;
                    break;
                }
            }
        } catch (Exception e) {
            b = false;
        }
        return b;
    }


    public static List<String> getYearList(LocalDateTime localDateTime,int num){
        List<String> yearList=new ArrayList<>();
        String nowYear = localDateTime.format(DateTimeFormatter.ofPattern("yyyy"));
        yearList.add(nowYear);
        for (int i=1;i<num;i++){
            String yyyy = localDateTime.plusYears(i).format(DateTimeFormatter.ofPattern("yyyy"));
            yearList.add(yyyy);
        }
        return yearList;
    }

    public static List<String> getAllMonthList(){
        List<String> months=new ArrayList<>();
        for (int i=1;i<=12;i++){
            if (i<10){
                String month="0"+i;
                months.add(month);
            }else {
                months.add(String.valueOf(i));
            }
        }
        return months;
    }

    // 时间格式,根据需要调整
    private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
    private static final DateTimeFormatter L_YYYY_MM_DD = DateTimeFormatter.ofPattern("yyyy/MM/dd");

    /**
     * 比较两个字符串表示的日期时间
     *
     * @param dateStr1 第一个日期时间字符串
     * @param dateStr2 第二个日期时间字符串
     * @return 如果dateStr1在dateStr2之前返回-1,相等返回0,之后返回1
     */
    public static int compare(String dateStr1, String dateStr2) {
        YearMonth dateTime1 = YearMonth.parse(dateStr1, formatter);
        YearMonth dateTime2 = YearMonth.parse(dateStr2, formatter);
        return dateTime1.compareTo(dateTime2);
    }

    /**
     * 计算两个日期之间的年差和月差,月差不超过11个月
     *
     * @param startDate 开始日期
     * @param endDate   结束日期
     * @return 年差和月差,格式为 "X年Y月",其中Y不超过11
     */
    public static String calculateYearMonthDifferenceLimited(LocalDate startDate, LocalDate endDate) {
        int years = (int) ChronoUnit.YEARS.between(startDate, endDate);
        LocalDate tempEndDate = endDate.minusYears(years);
        int months = (int) ChronoUnit.MONTHS.between(startDate, tempEndDate);

        // 如果月份差超过11个月,则月份差设为11个月
        if (months > 11) {
            months = 11;
            // 注意:这里我们不增加年份,因为我们已经有了完整的年份差
        }

        if (years == 0){
            return  months + "月";
        }else if (months == 0) {
            return years + "年" ;
        }else {
            return years + "年" + months + "月";
        }
    }

    /*
    * 格式化日期 日期只能是 xxxx.xx格式的进行转化
    * */
    public static LocalDate dateConvertUnit(String dateStr){
            String[] parts = dateStr.split("\\.");
            int year = Integer.parseInt(parts[0]);
            int month = Integer.parseInt(parts[1]);
            // 构建该月的第一天
            LocalDate date = LocalDate.of(year, month, 1);
            return date;
    }

    public static int dateSubtraction(String startDate,String endDate){
        if (isEmpty(startDate)){
            return 0;
        }
        if (isEmpty(endDate)){
            return 0;
        }
        LocalDate parseStart = LocalDate.parse(startDate, L_YYYY_MM_DD);
        LocalDate parseEnd = LocalDate.parse(endDate, L_YYYY_MM_DD);
        Period period = Period.between(parseStart, parseEnd);
        int years = period.getYears();
        int months = period.getMonths();
        int days = period.getDays();
        if (years>0){
            BigDecimal bigDecimal = BigDecimal.valueOf(years);
            BigDecimal multiply = bigDecimal.multiply(new BigDecimal(12));
            months=multiply.add(new BigDecimal(months)).intValue();
        }
        if (months>0){
            BigDecimal bigDecimal = BigDecimal.valueOf(months);
            BigDecimal multiply = bigDecimal.multiply(new BigDecimal(30));
            days=multiply.add(new BigDecimal(days)).intValue();
        }
        if (days<=30){
            return 1;
        }else {
            BigDecimal bigDecimal = BigDecimal.valueOf(days);
            BigDecimal divide = bigDecimal.divide(new BigDecimal(30),  BigDecimal.ROUND_HALF_UP);
            return divide.intValue();
        }
    }

    /*
    * @Author QH
    * @Description 获取指定时间到指定时间23:59:59相差多少分钟
    * @Date 10:57 2024/8/14/周三
    * @Param now
    * @return
    **/
    public static long getDifferenceValue(LocalDateTime now){
        // 构造当天的日期但时间设置为23:59:59
        LocalDateTime endOfDay = now.withHour(23).withMinute(59).withSecond(59);
        // 计算时间差
        long minutesDifference = ChronoUnit.MINUTES.between(now, endOfDay);
        return minutesDifference;
    }

    /*
    * @Author QH
    * @Description 讲日期字符串转换为 YYYY年MM月DD日 格式
    * @Date 10:14 2024/9/9
    * @Param formatter、date
    * @return
    **/
    public static final String getChinessDate(String formatter,String date){
        if (StringUtils.isEmpty(date) || StringUtils.isEmpty(formatter)){
            return "";
        }
        Date date1 = dateTime(formatter, date);
        String s = parseDateToStr("yyyy年MM月dd日", date1);
        return s;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值