Java日期时间互相转换方法(Date、LocalDateTime、时间戳、时间字符串相互转换)及完整日期时间工具类(各种日期时间运算及获取)

1.Date转LocalDateTime、时间戳、中文字符串

  	/**
     * 获取当前Date
     */
    public static Date getNowToDate() {
    
    
        return new Date();
    }

    /**
     * Date转LocalDateTime
     */
    public static LocalDateTime dateToLocalDateTime(Date date) {
    
    
        if (date == null) {
    
    
            return null;
        }
        return date.toInstant().atZone(ZONE_ID).toLocalDateTime();
    }

    /**
     * Date转时间戳(毫秒数)
     */
    public static Long dateToLong(Date date) {
    
    
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.getTimeInMillis();
    }

    /**
     * Date转String
     */
    public static String dateToString(Date date, String sFormat) {
    
    
        return date == null || StringUtils.isEmpty(sFormat) ? null : FastDateFormat.getInstance(sFormat).format(date);
    }

2.LocalDateTime转Date、时间戳、中文字符串

 /**
     * 获取当前LocalDateTime
     */
    public static LocalDateTime getNowToLocalDateTime() {
    
    
        return LocalDateTime.now();
    }

    /**
     * LocalDateTime转Date
     */
    public static Date localDateTimeToDate(LocalDateTime ldt) {
    
    
        return ldt == null ? null : new Date(ldt.toInstant(ZoneOffset.ofHours(8)).toEpochMilli());
    }

    /**
     * LocalDateTime转时间戳
     */
    public static Long localDateTimeToLong(LocalDateTime ldt) {
    
    
        return ldt == null ? null : ldt.toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
    }

    /**
     * LocalDateTime转String
     */
    public static String localDateTimeToString(LocalDateTime ldt, String sFormat) {
    
    
        return ldt == null || StringUtils.isEmpty(sFormat) ? null : ldt.format(DateTimeFormatter.ofPattern(sFormat));
    }

3.时间戳转Date、LocalDateTime、中文字符串

    /**
     * 获取当前时间戳
     */
    public static Long getNowToLong() {
    
    
        return System.currentTimeMillis();
    }

    /**
     * 时间戳转Date
     */
    public static Date longToDate(Long timestamp) {
    
    
        return timestamp == null ? null : new Date(timestamp);
    }

    /**
     * 时间戳转LocalDateTime
     */
    public static LocalDateTime longToLocalDateTime(Long timestamp) {
    
    
        return timestamp == null ? null : LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneOffset.ofHours(8));
    }

    /**
     * 时间戳转String
     */
    public static String longToString(Long timestamp, String sFormat) {
    
    
        if (timestamp == null || timestamp <= 0 || sFormat == null || sFormat.isEmpty()) {
    
    
            return null;
        }
        Date date = new Date(timestamp);
        return DateUtil.dateToString(date, sFormat);
    }

4.中文字符串转Date、LocalDateTime、时间戳

	/**
     * 获取当前时间String
     */
    public static String getNowToString(String sFormat) {
    
    
        return dateToString(new Date(), sFormat);
    }

    /**
     * 时间字符串转Date
     */
    public static Date stringToDate(String sDate, String sFormat) {
    
    
        try {
    
    
            FastDateFormat fastDateFormat = FastDateFormat.getInstance(sFormat);
            return fastDateFormat.parse(sDate);
        } catch (ParseException e) {
    
    
            LOGGER.error("Parse date exception: {}", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 时间字符串转LocalDateTime
     */
    public static LocalDateTime stringToLocalDateTime(String sDate, String sFormat) {
    
    
        if (StringUtils.isEmpty(sDate) || StringUtils.isEmpty(sFormat)) {
    
    
            return null;
        }
        return  LocalDateTime.parse(sDate, DateTimeFormatter.ofPattern(sFormat));
    }

    /**
     * 时间字符串转时间戳
     */
    public static Long stringToLong(String sDate, String sFormat) {
    
    
        if (StringUtils.isEmpty(sDate) || StringUtils.isEmpty(sFormat)) {
    
    
            return null;
        }
        return stringToLocalDateTime(sDate, sFormat).toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
    }

5.测试及效果展示

    public static void main(String[] args) {
    
    
    	String SIMPLE_FMT = "yyyy-MM-dd HH:mm:ss";
        //Date、LocalDateTime、时间戳、中文字符串相互转换
        //1.获取现在Date
        Date date = DateUtil.getNowToDate();
        //Date转LocalDateTime
        LocalDateTime localDateTime = DateUtil.dateToLocalDateTime(date);
        //Date转时间戳
        Long timeLong = DateUtil.dateToLong(date);
        //Date转中文字符串
        String timeString = DateUtil.dateToString(date, SIMPLE_FMT);
        System.out.println("date=("+date+");localDateTime=("+localDateTime+");timeLong=("+timeLong+");timeString=("+timeString+")");

        //2.获取现在LocalDateTime
        LocalDateTime localDateTime1 = DateUtil.getNowToLocalDateTime();
        //LocalDateTime转Date
        Date date1 = DateUtil.localDateTimeToDate(localDateTime1);
        //LocalDateTime转时间戳
        Long timeLong1 = DateUtil.localDateTimeToLong(localDateTime1);
        //LocalDateTime转中文字符串
        String timeString1 = DateUtil.localDateTimeToString(localDateTime1, SIMPLE_FMT);
        System.out.println("date1=("+date1+");localDateTime1=("+localDateTime1+");timeLong1=("+timeLong1+");timeString1=("+timeString1+")");


        //3.获取现在时间戳
        Long timeLong2 = DateUtil.getNowToLong();
        //时间戳转Date
        Date date2 = DateUtil.longToDate(timeLong2);
        //时间戳转LocalDateTime
        LocalDateTime localDateTime2 = DateUtil.longToLocalDateTime(timeLong2);
        //时间戳转中文字符串
        String timeString2 = DateUtil.longToString(timeLong2, SIMPLE_FMT);
        System.out.println("date2=("+date2+");localDateTime2=("+localDateTime2+");timeLong2=("+timeLong2+");timeString2=("+timeString2+")");



        //4.获取现在中文字符串
        String timeString3 = DateUtil.getNowToString(SIMPLE_FMT);
        //中文字符串转Date
        Date date3 = DateUtil.stringToDate(timeString3, SIMPLE_FMT);
        //中文字符串转LocalDateTime
        LocalDateTime localDateTime3 = DateUtil.stringToLocalDateTime(timeString3, SIMPLE_FMT);
        //中文字符串转时间戳
        Long timeLong3 = DateUtil.stringToLong(timeString3, SIMPLE_FMT);
        System.out.println("date3=("+date3+");localDateTime3=("+localDateTime3+");timeLong3=("+timeLong3+");timeString3=("+timeString3+")");
    }

在这里插入图片描述

6.完整时间工具类DateUtil介绍

以下是代码中包含的时间运算及获取方法的总结:

一、时间获取方法

  1. 当前时间获取

    • getNowToDate(): 获取当前Date
    • getNowToLocalDateTime(): 获取当前LocalDateTime
    • getNowToLong(): 获取当前时间戳(毫秒)
    • getNowToString(String sFormat): 获取当前时间字符串(指定格式)
  2. 特定时间点获取

    • getFirstDayOfMonth(Date date): 获取月份第一天
    • getLastDayOfMonth(Date date): 获取月份最后一天
    • getYearFirst(int year): 获取某年第一天
    • getYearLast(int year): 获取某年最后一天
    • getCurrYearFirst(): 获取当年第一天
    • getCurrYearLast(): 获取当年最后一天

二、时间转换方法

  1. 类型转换

    • dateToLocalDateTime(Date date): Date转LocalDateTime
    • localDateTimeToDate(LocalDateTime ldt): LocalDateTime转Date
    • dateToLong(Date date): Date转时间戳
    • localDateTimeToLong(LocalDateTime ldt): LocalDateTime转时间戳
    • longToDate(Long timestamp): 时间戳转Date
    • longToLocalDateTime(Long timestamp): 时间戳转LocalDateTime
  2. 字符串转换

    • dateToString(Date date, String sFormat): Date转字符串
    • localDateTimeToString(LocalDateTime ldt, String sFormat): LocalDateTime转字符串
    • longToString(Long timestamp, String sFormat): 时间戳转字符串
    • stringToDate(String sDate, String sFormat): 字符串转Date
    • stringToLocalDateTime(String sDate, String sFormat): 字符串转LocalDateTime
    • stringToLong(String sDate, String sFormat): 字符串转时间戳

三、时间运算方法

  1. 时间加减

    • plusYears(Date date, int amount): 增加/减少年
    • plusMonths(Date date, int amount): 增加/减少月
    • plusDays(Date date, int amount): 增加/减少天
    • plusHours(Date date, int amount): 增加/减少小时
    • plusMinutes(Date date, int amount): 增加/减少分钟
    • plusSeconds(Date date, int amount): 增加/减少秒
    • plusMilliseconds(Date date, int amount): 增加/减少毫秒
    • offsetYear(Date date, Integer offsetYear): 年份偏移
    • offsetMonth(Date date, Integer offsetMonth): 月份偏移
  2. 时间差计算

    • caculateDayDiff(Date begin, Date end): 计算天数差
    • rangeTime(Date startTime, Date endTime, Integer seekType): 计算时间间隔(年/月/天)
  3. 特殊日期处理

    • getNextWorkDay(LocalDate date, List<LocalDate> holidays): 获取下一个工作日
    • getOpWorkDay(LocalDate date, List<LocalDate> holidays): 获取操作日(跳过节假日)
    • getCurrentSunDay(LocalDate date): 获取当前日期的下一个周日

四、时间格式化方法

  1. 标准格式

    • parseDateToMString(Date date): 格式化为"yyyy年MM月"
    • parseDateToZHString(Date date): 格式化为"yyyy年MM月dd日"
    • parseStandardToString(Date date): 格式化为"yyyy-MM-dd"
    • parseSimpleateToString(Date date): 格式化为"yyyy-MM-dd HH:mm:ss"
  2. 智能格式化

    • smartDateToString(Date date, String sFormat): 去除末尾的"00:00:00"

五、时间属性获取

  1. 日期分解

    • getYear(Date date): 获取年份
    • getMonth(Date date): 获取月份(1-12)
    • getDay(Date date): 获取日
    • getDayOfWeek(Date date): 获取星期(0-6)
    • getDayOfMonth(Date date): 获取当月第几天
    • getDayOfYear(Date date): 获取当年第几天
  2. 其他属性

    • getDaysByYearMonth(Date date): 获取月份总天数
    • checkTheSameMonth(Date date1, Date date2): 判断是否同月份

六、扩展功能

  1. 时区处理

    • 所有时间转换均使用系统默认时区ZONE_ID
  2. 边界设置

    • setDefaultEndDate(Date date): 设置当天结束时间(23:59:59)
  3. 时间校验

    • belongCalendar(Date nowTime, Date beginTime, Date endTime): 判断时间是否在区间内

该工具类提供了完整的时间操作功能,覆盖了Java 8之前和之后的日期处理方式,支持多种格式转换、复杂时间运算和特殊场景处理。

七、完整DateUtil.java代码下载

完整代码下载地址:https://download.csdn.net/download/weixin_44330367/90518760

猜你喜欢

转载自blog.csdn.net/weixin_44330367/article/details/146418960
今日推荐