yanghb
2024-12-24 fe6e43d5e1144156d0ca4e9d6080c9821c25d97c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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月"));
    }
 
}