| | |
| | | import java.text.ParseException; |
| | | import java.text.SimpleDateFormat; |
| | | import java.time.Duration; |
| | | import java.time.LocalDate; |
| | | import java.time.Period; |
| | | import java.time.format.DateTimeFormatter; |
| | | import java.util.*; |
| | | |
| | | /** |
| | |
| | | public static final String DATE_FORMATE_STRING_N = "HHmmss"; |
| | | public static final String DATE_FORMATE_STRING_O = "yyyyMMddHHmm"; |
| | | public static final String DATE_FORMATE_STRING_Q = "yyyy-MM"; |
| | | private static final DateTimeFormatter DEFAULT_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd"); |
| | | |
| | | |
| | | static { |
| | |
| | | |
| | | return result.toString(); |
| | | } |
| | | |
| | | /** |
| | | * 计算两个字符串日期之间的月数(超过一个整月则+1) |
| | | * @param startDateStr 开始日期字符串(格式:yyyy-MM-dd) |
| | | * @param endDateStr 结束日期字符串(格式:yyyy-MM-dd) |
| | | * @return 月数差 |
| | | */ |
| | | public static int calculateMonths(String startDateStr, String endDateStr) { |
| | | // 1. 将字符串解析为LocalDate |
| | | LocalDate startDate = LocalDate.parse(startDateStr, DEFAULT_FORMATTER); |
| | | LocalDate endDate = LocalDate.parse(endDateStr, DEFAULT_FORMATTER); |
| | | // 2. 确保开始日期在结束日期之前 |
| | | if (startDate.isAfter(endDate)) { |
| | | LocalDate temp = startDate; |
| | | startDate = endDate; |
| | | endDate = temp; |
| | | } |
| | | // 3. 计算完整月数 |
| | | Period period = Period.between(startDate, endDate); |
| | | int fullMonths = period.getYears() * 12 + period.getMonths(); |
| | | |
| | | // 4. 若天数差>0,说明超过整月,额外加1 |
| | | if (period.getDays() > 0) { |
| | | fullMonths++; |
| | | } |
| | | return fullMonths; |
| | | } |
| | | |
| | | } |