JAVA LocalDateTime.class,LocalDate.class,Date.class 工具类,来优化让人反感的项目

文章目录

概要

LocalDateTime.class,LocalDate.class,Date.class 常用工具类`

在实际开发过程中,我发现很多时候进行时间操作时直接编写代码
在这里插入图片描述

这种方式存在一个严重的问题:相同的代码被复制粘贴到项目的各个部分,导致代码冗余度增加且维护困难。显然,相同逻辑的代码应该封装起来以提高代码的复用性和可维护性。为此,我整理并封装了一些常用的时间操作方法,包括对不同时间类型(如LocalDateTimeLocalDateDate)的支持,实现了诸如调整给定或当前时间、格式化日期时间、获取系统当前时间戳、计算两个时间之间的差异以及判断当前时间是否处于某个时间区间等常见功能。这些封装不仅减少了重复代码,还提高了代码的清晰度和健壮性,使得时间处理更加简便和直观。通过这样的封装,可以有效提升开发效率,并减少因手动编写时间操作代码而可能引发的错误。

工具类代码

package com.huiHang;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class DateUtils {
    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");


    public static void main(String[] args) {
        LocalDate now = LocalDate.now();
        System.out.println(now);
    }

    /**
     * 调整给定或当前时间,支持基于年、月和日的加减。
     * @param clazz 时间类类型,可以是 LocalDateTime.class, LocalDate.class, 或 Date.class。
     * @param years 年的加减值。
     * @param months 月的加减值。
     * @param days 日的加减值。
     * @return 返回与输入时间类型相同的时间对象。
     */
    public static Object adjustDateTime(Class<?> clazz, int years, int months, int days) {
        if (clazz.equals(LocalDateTime.class)) {
            return LocalDateTime.now().plusYears(years).plusMonths(months).plusDays(days);
        } else if (clazz.equals(LocalDate.class)) {
            return LocalDate.now().plusYears(years).plusMonths(months).plusDays(days);
        } else if (clazz.equals(Date.class)) {
            Instant instant = new Date().toInstant();
            LocalDateTime localDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
            LocalDateTime adjustedLocalDateTime = localDateTime.plusYears(years).plusMonths(months).plusDays(days);
            return Date.from(adjustedLocalDateTime.atZone(ZoneId.systemDefault()).toInstant());
        } else {
            throw new IllegalArgumentException("Unsupported time type");
        }
    }


    /**
     * date日期格式化 yyyy-MM-dd
     * @param time
     * @return
     */
    public static String dateFormatter(Object time) {
        return getString(time, DATE_FORMATTER);
    }

    /**
     * datetime日期格式化 yyyy-MM-dd HH:mm:ss
     * @param time
     * @return
     */
    public static String datetimeFormatter(Object time) {
        return getString(time, DATE_TIME_FORMATTER);
    }
    
    public static String getString(Object time, DateTimeFormatter formatter) {
        if (time instanceof LocalDateTime) {
            return ((LocalDateTime) time).format(formatter);
        } else if (time instanceof LocalDate) {
            return ((LocalDate) time).format(formatter);
        } else if (time instanceof Date) {
            Instant instant = ((Date) time).toInstant();
            LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
            if (formatter.equals(DATE_FORMATTER)) {
                return localDateTime.toLocalDate().format(formatter);
            } else {
                return localDateTime.format(formatter);
            }
        } else {
            throw new IllegalArgumentException("Unsupported time type");
        }
    }


    /**
     * 获取系统当前时间戳
     */
    public String getSystemTime() {
        return String.valueOf(System.currentTimeMillis());
    }


    /**
     * 获得当前日期 yyyy-MM-dd HH:mm:ss 或 yyyy-MM-dd 根据 T 的类型
     */
    public <T> T getCurrentTime(Class<T> clazz) {
        if (clazz.equals(LocalDateTime.class)) {
            return clazz.cast(LocalDateTime.now());
        } else if (clazz.equals(LocalDate.class)) {
            return clazz.cast(LocalDate.now());
        } else if (clazz.equals(Date.class)) {
            return clazz.cast(Date.from(Instant.now()));
        } else {
            throw new IllegalArgumentException("Unsupported time type");
        }
    }

    /**
     * 获取当前日期 yyyy-MM-dd 或 yyyy-MM-dd HH:mm:ss 根据 T 的类型
     */
    public <T> String getDateByString(Class<T> clazz) {
        if (clazz.equals(LocalDateTime.class)) {
            return LocalDateTime.now().format(DATE_TIME_FORMATTER);
        } else if (clazz.equals(LocalDate.class)) {
            return LocalDate.now().format(DATE_FORMATTER);
        } else if (clazz.equals(Date.class)) {
            return new Date().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime().format(DATE_TIME_FORMATTER);
        } else {
            throw new IllegalArgumentException("Unsupported time type");
        }
    }

    /**
     * 得到两个时间差 格式yyyy-MM-dd HH:mm:ss
     */
    public long dateSubtraction(Object start, Object end) {
        LocalDateTime startTime = null;
        LocalDateTime endTime = null;

        if (start instanceof LocalDateTime) {
            startTime = (LocalDateTime) start;
        } else if (start instanceof Date) {
            startTime = LocalDateTime.ofInstant(((Date) start).toInstant(), ZoneId.systemDefault());
        } else {
            throw new IllegalArgumentException("Unsupported start time type");
        }

        if (end instanceof LocalDateTime) {
            endTime = (LocalDateTime) end;
        } else if (end instanceof Date) {
            endTime = LocalDateTime.ofInstant(((Date) end).toInstant(), ZoneId.systemDefault());
        } else {
            throw new IllegalArgumentException("Unsupported end time type");
        }

        return Duration.between(startTime, endTime).toMillis();
    }

    /**
     * 判断当前时间是否在[startTime, endTime]区间
     */
    public <T> boolean isEffectiveDate(T nowTime, String dateSection, Class<T> clazz) {
        String[] times = dateSection.split(",");
        LocalDate startTime = LocalDate.parse(times[0], DATE_FORMATTER);
        LocalDate endTime = LocalDate.parse(times[1], DATE_FORMATTER);

        if (clazz.equals(LocalDate.class)) {
            LocalDate localNowDate = (LocalDate) nowTime;
            return !localNowDate.isBefore(startTime) && !localNowDate.isAfter(endTime);
        } else if (clazz.equals(Date.class)) {
            Instant instant = ((Date) nowTime).toInstant();
            LocalDate localNowDate = LocalDateTime.ofInstant(instant, ZoneId.systemDefault()).toLocalDate();
            return !localNowDate.isBefore(startTime) && !localNowDate.isAfter(endTime);
        } else {
            throw new IllegalArgumentException("Unsupported now time type");
        }
    }


    /**
     * 判断当前时间是否在[startTime, endTime]区间
     */
    public <T> boolean isEffectiveDate(T nowTime, T startTime, T endTime, Class<T> clazz) {
        if (clazz.equals(LocalDate.class)) {
            LocalDate nowLocalDate = (LocalDate) nowTime;
            LocalDate startLocalDate = (LocalDate) startTime;
            LocalDate endLocalDate = (LocalDate) endTime;
            return !nowLocalDate.isBefore(startLocalDate) && !nowLocalDate.isAfter(endLocalDate);
        } else if (clazz.equals(LocalDateTime.class)) {
            LocalDateTime nowLocalDateTime = (LocalDateTime) nowTime;
            LocalDateTime startLocalDateTime = (LocalDateTime) startTime;
            LocalDateTime endLocalDateTime = (LocalDateTime) endTime;
            return !nowLocalDateTime.isBefore(startLocalDateTime) && !nowLocalDateTime.isAfter(endLocalDateTime);
        } else if (clazz.equals(java.util.Date.class)) {
            Instant nowInstant = ((java.util.Date) nowTime).toInstant();
            Instant startInstant = ((java.util.Date) startTime).toInstant();
            Instant endInstant = ((java.util.Date) endTime).toInstant();
            return !nowInstant.isBefore(startInstant) && !nowInstant.isAfter(endInstant);
        } else {
            throw new IllegalArgumentException("Unsupported time type");
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小电玩

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

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

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

打赏作者

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

抵扣说明:

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

余额充值