package com.zzg.common.utils;
|
|
import java.time.LocalDate;
|
import java.time.Period;
|
import java.time.format.DateTimeFormatter;
|
import java.util.HashMap;
|
import java.util.Map;
|
|
public class LocalDateUtils {
|
|
/**
|
* 年月日格式化方式
|
*/
|
public static String YYYY = "yyyy";
|
public static String YYYYY = "yyyy年";
|
|
public static String YYYY_MM = "yyyy-MM";
|
public static String YYYYYMMM = "yyyy年MM月";
|
|
public static String YYYY_MM_DD = "yyyy-MM-dd";
|
public static String YYYYYMMMDDD = "yyyy年MM月dd日";
|
|
public static String YYYYMMDD = "yyyyMMdd";
|
|
/**
|
* 获取时间差(月份数和天数)
|
*
|
* @param startDate
|
* @param endDate
|
* @return
|
*/
|
public static Map<String, Integer> timeDifference(LocalDate startDate, LocalDate endDate) {
|
// 计算两个日期之间的差值
|
Period period = Period.between(startDate, endDate);
|
|
// 获取相差的月数和天数
|
int diffMonths = period.getYears() * 12 + period.getMonths();
|
int diffDays = period.getDays();
|
Map<String, Integer> map = new HashMap<>();
|
|
map.put("month", diffMonths);
|
map.put("day", diffDays);
|
|
return map;
|
}
|
|
/**
|
* 时间格式转换
|
* date转string(yyyy-MM-dd)
|
*
|
* @param date
|
* @return
|
*/
|
public static String localDateToString(LocalDate date) {
|
return localDateToString(date, YYYY_MM_DD);
|
}
|
|
public static String localDateToString(LocalDate date, String formatter) {
|
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(formatter);
|
// 使用格式化器将 LocalDate 转换为字符串
|
return date.format(dateTimeFormatter);
|
}
|
|
public static void main(String[] args) {
|
// 假设有两个日期
|
LocalDate startDate = LocalDate.of(2021, 1, 1);
|
LocalDate endDate = LocalDate.of(2021, 5, 1);
|
System.out.println(localDateToString(startDate, "yyyy年MM月"));
|
}
|
|
}
|