hutool 日期转换

发布时间 2023-04-27 09:56:40作者: 全琪俊
DateTime转LocalDate
DateTime useTimeDate = DateUtil.offsetMonth(date, 12);
LocalDateTime useTime = DateUtil.toLocalDateTime(useTimeDate);

字符串转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);