需求背景
我们的项目使用了按月分库,命名格式为:order_202407,order_202408,在编写分库策略的代码时,需要根据入参里的业务开始时间和业务结束时间,来定位到目标表
代码
public static List<String> getMonthList(LocalDateTime startDate, LocalDateTime endDate) {
List<String> monthList = new ArrayList<>();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
// 确保 startDate 在 endDate 之前
if (startDate.isAfter(endDate)) {
LocalDateTime temp = startDate;
startDate = endDate;
endDate = temp;
}
// 从 startDate 开始循环,直到达到 endDate
while (startDate.isBefore(endDate) || startDate.equals(endDate)) {
monthList.add(startDate.format(formatter));
// 移动到下一个月的第一天
startDate = startDate.plusMonths(1).withDayOfMonth(1);
}
return monthList;
}
public static void main(String[] args) {
// 示例日期
LocalDateTime dateA = LocalDateTime.of(2024, 7, 15, 10, 30);
LocalDateTime dateB = LocalDateTime.of(2024, 8, 1, 14, 45);
// 调用工具类方法获取月份列表
List<String> monthList = getMonthList(dateA, dateB);
// 打印结果
for (String month : monthList) {
System.out.println(month);
}
}
结语
通过这个方法,可以得到目标表