首页 > 其他分享 >日期工具类-操作字符串和Date、LocalDate互转,两个日期的时间差等

日期工具类-操作字符串和Date、LocalDate互转,两个日期的时间差等

时间:2022-12-10 16:31:22浏览次数:58  
标签:return format Date 日期 dateStr date 互转 null

避免重复造轮子,相关方法基于hutool日期时间工具封装并做部分增强。需要先引入如下坐标

          <dependency>
              <groupId>cn.hutool</groupId>
              <artifactId>hutool-all</artifactId>
              <version>${hutool.version}</version>
          </dependency>

字符串转Date

    //字符串转Date
    Date dateTime = DateUtil.parseDate("2022-04-06");
    System.out.println(dateTime);

Date转字符串

//Date转字符串不指定format格式,默认yyyy-MM-dd HH:mm:ss
String dateStr = DateUtil.date2Str(new Date());
System.out.println(dateStr);
//Date转字符串指定格式
String dateStr2 = DateUtil.date2Str("yyyy/MM/dd",new Date());
System.out.println(dateStr2);

字符串转LocalDate

//字符串转LocalDate
LocalDate localDate = DateUtil.parseLocalDate("2022-04-06");
System.out.println(localDate);

Date转LocalDate

//Date转LocalDate
LocalDate localDate = DateUtil.date2LocalDate(new Date());
System.out.println(localDate);

LocalDate转字符串

//LocalDate转Str
String localDateStr = DateUtil.localDate2Str(LocalDate.now());
System.out.println(localDateStr);

两个日期的时间差

String beginDateStr = "2022-02-01 22:33:23";
Date beginDate = DateUtil.parse(beginDateStr);

String endDateStr = "2022-03-10 23:33:23";
Date endDate = DateUtil.parse(endDateStr);
//相差天数(37)
long betweenDay = DateUtil.between(beginDate, endDate, DateUnit.DAY);
System.out.println(betweenDay);
//格式化时间差(37天1小时)
String formatBetween = DateUtil.formatBetween(beginDate, endDate, BetweenFormater.Level.HOUR);
System.out.println(formatBetween);

一天的开始和结束时间

String dateStr = "2022-04-07 10:33:23";
Date date = DateUtil.parse(dateStr);

//一天的开始时间:2022-04-07 00:00:00
Date beginOfDay = DateUtil.beginOfDay(date);
System.out.println(beginOfDay);

//一天的结束时间:2022-04-07 23:59:59
Date endOfDay = DateUtil.endOfDay(date);
System.out.println(endOfDay);

工具类如下:

/**
 * <p>基于hutool的日期工具类增强</p>
 *
 * @author zjq
 * @date 2021/04/07
 */
public class DateUtil extends cn.hutool.core.date.DateUtil {

    private static final String[] PARSE_PATTERNS = {
            "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",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    public static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HH:mm:ss");
    public static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    public static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 字符串转date类型
     *
     * @param dateStr
     * @return
     */
    public static Date parseDate(Object dateStr) {
        if (ObjectUtils.isNull(dateStr)) {
            return null;
        }
        if (dateStr instanceof Double) {
            return org.apache.poi.ss.usermodel.DateUtil.getJavaDate((Double) dateStr);
        }
        return parse(dateStr.toString(), PARSE_PATTERNS);
    }

    /**
     * Date类型转字符串
     *
     * @param date
     * @return yyyy-MM-dd HH:mm:ss
     */
    public static String date2Str(Date date) {
        return date2Str(null, date);
    }

    /**
     * Date类型转字符串
     *
     * @param format
     * @param date
     * @return
     */
    public static String date2Str(String format, Date date) {
        if (ObjectUtils.isNull(date)) {
            return null;
        }
        SimpleDateFormat dateFormat = StrUtil.isNotBlank(format) ?new SimpleDateFormat(format):
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return dateFormat.format(date);
    }

    /**
     * 字符串转LocalTime类型
     *
     * @param dateStr
     * @return
     */
    public static LocalTime parseLocalTime(Object dateStr) {
        if (ObjectUtils.isNull(dateStr)) {
            return null;
        }
        if (dateStr instanceof Double) {
            return date2LocalTime(parseDate(dateStr));
        }
        return LocalTime.parse(dateStr.toString(), TIME_FORMATTER);
    }

    /**
     * Date转LocalTime
     *
     * @param date
     * @return
     */
    public static LocalTime date2LocalTime(Date date) {
        if (null == date) {
            return null;
        }
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalTime();
    }

    /**
     * LocalTime转Str
     *
     * @param localTime
     * @return HH:mm:ss
     */
    public static String localTime2Str(LocalTime localTime) {
        return localTime2Str(null, localTime);
    }

    /**
     * LocalTime转str
     *
     * @param format    格式
     * @param localTime
     * @return
     */
    public static String localTime2Str(String format, LocalTime localTime) {
        if (null == localTime) {
            return null;
        }
        DateTimeFormatter formatter = StrUtil.isBlank(format) ?
                TIME_FORMATTER : DateTimeFormatter.ofPattern(format);
        return localTime.format(formatter);
    }

    /**
     * 字符串转LocalDate类型
     *
     * @param dateStr
     * @return
     */
    public static LocalDate parseLocalDate(Object dateStr) {
        if (ObjectUtils.isNull(dateStr)) {
            return null;
        }
        if (dateStr instanceof Double) {
            return date2LocalDate(parseDate(dateStr));
        }
        return LocalDate.parse(dateStr.toString(), DATE_FORMATTER);
    }

    /**
     * Date转LocalDate
     *
     * @param date
     * @return
     */
    public static LocalDate date2LocalDate(Date date) {
        if (null == date) {
            return null;
        }
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    }

    /**
     * LocalDate转Str
     *
     * @param localDate
     * @return
     */
    public static String localDate2Str(LocalDate localDate) {
        return localDate2Str(null, localDate);
    }

    /**
     * LocalDate转Str
     *
     * @param format    格式
     * @param localDate
     * @return
     */
    public static String localDate2Str(String format, LocalDate localDate) {
        if (null == localDate) {
            return null;
        }
        DateTimeFormatter formatter = StrUtil.isBlank(format) ?
                DATE_FORMATTER : DateTimeFormatter.ofPattern(format);
        return localDate.format(formatter);
    }

    /**
     * 字符串转LocalDateTime类型
     *
     * @param dateStr
     * @return
     */
    public static LocalDateTime parseLocalDateTime(Object dateStr) {
        if (ObjectUtils.isNull(dateStr)) {
            return null;
        }
        if (dateStr instanceof Double) {
            return date2LocalDateTime(parseDate(dateStr));
        }
        return LocalDateTime.parse(dateStr.toString(), DATETIME_FORMATTER);
    }

    /**
     * Date转LocalDateTime
     *
     * @param date
     * @return
     */
    public static LocalDateTime date2LocalDateTime(Date date) {
        if (null == date) {
            return null;
        }
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    }

    /**
     * LocalDate转Str
     *
     * @param localDateTime
     * @return
     */
    public static String localDateTime2Str(LocalDateTime localDateTime) {
        return localDateTime2Str(null, localDateTime);
    }

    /**
     * LocalDate转Str
     *
     * @param format
     * @param localDateTime
     * @return
     */
    public static String localDateTime2Str(String format, LocalDateTime localDateTime) {
        if (null == localDateTime) {
            return null;
        }
        DateTimeFormatter formatter = StrUtil.isBlank(format) ?
                DATETIME_FORMATTER : DateTimeFormatter.ofPattern(format);
        return localDateTime.format(formatter);
    }
}

参考:https://www.hutool.cn/docs/#/core/日期时间/日期时间工具-DateUtil

本文内容到此结束了, 如有收获欢迎点赞

标签:return,format,Date,日期,dateStr,date,互转,null
From: https://blog.51cto.com/zhanjq/5927800

相关文章

  • Python | time和datetime模块详解
    对时间进行处理 python与时间处理相关的模块有两个:time模块和datetime模块(python的内置标准库,不需要去下载)datetime模块,常用类4个(date,time,datetime,timedelta)......
  • moment.js 获取国内自燃周开始时间与结束时间以及当前日期第几周
    /***国内自然周*/constgetWeekOfNature=(date,format)=>{letweekOfday=moment(date).format("E");//计算是这周第几天letmonday=moment(date).subtract(week......
  • C++日期和时间编程总结
    在C++11之前,C++编程只能使用C-style日期时间库,其精度只有秒级别,这对于有高精度要求的程序来说,是不够的。但这个问题在C++11中得到了解决,C++11中不仅扩展了......
  • 前端开发系列021-基础篇之日期类型和计时器
    title:'前端开发系列021-基础篇之日期类型和计时器'tags:-javaScript系列categories:[]date:2017-06-1808:20:13本文介绍JavaScript语言中的Date日期类型,常......
  • 前端开发系列010-基础篇之JavaScript的Date对象
    title:'前端开发系列010-基础篇之JavaScript的Date对象'tags:-javaScript系列categories:[]date:2017-05-1219:27:10本文介绍JavaScript中的内置对象Date,时......
  • 第一百一十一篇:基本引用类型Date
    好家伙,本篇为《JS高级程序设计》第五章的学习笔记 1.基本引用类型引用值(或者对象)是某个特定引用类型的实例,在ECMAScript中,引用类型是把数据和功能组织到一起的结构,(像极......
  • Java重点 | Date类
    Date类java.util.Date:表示日期和时间的类,Date表示特定的瞬间,精确到毫秒。毫秒值的概念与作用毫秒:千分之一秒,1000毫秒=1。秒特定的瞬间:一个时间点,一刹那时间例如......
  • 7. 内置对象Date
    内置对象:DateDate对象在实际开发中,使用得很频繁,且容易在细节地方出错,需要引起重视。内置对象Date用来处理日期和时间。需要注意的是:与Math对象不同,Date对象是一......
  • Winform自动更新之AutoUpdater.NET
     AutoUpdater.NET(https://github.com/ravibpatel/AutoUpdater.NET)的原理大致是从服务器上(IIS站点)下载包含更新信息的XML文件,通过下载的XML文件获取Winform等桌面......
  • ON DUPLICATE KEY UPDATE 导致mysql自增主键ID跳跃增长
    一.问题点:1.如果mysql表只是设置了联合主键且不包含自增的id,则使用ONDUPLICATEKEYUPDATE不会有问题2.如果mysql表设置了自增主键id,则使用ONDUPLICATEKEYUP......