传入年月,遍历中间所有的月份(包含起始月和结尾月份)
今天遇到个需求:选择两个月份,需要两个月中间的每个月的统计数据,原本的意思是从数据库直接查出来,再通过日期赋值。
但是考虑到这样一种情况:万一某个月中间没有数据,那岂不是为空!
所有还得遍历每一个月份,对于没有数据的月份,在对于月份中设置为0就行。
下面是我写的工具类:注意传入的格式(YYYY-MM)字符串类型的年和月
/**
* @Description:
* @author: wangyong
* @date: 2022年05月11日 20:36
*/
public class DateUtils {
/**
* 传入年月,遍历中间所有的月份(包含起始月和结尾月份)
* @param startDate 起始月 yyyy-mm
* @param endDate 结束月 yyyy-mm
* @return
*/
public static List<String> getBetweenYearMonth(String startDate,String endDate){
Integer startY = Integer.valueOf(startDate.split("-")[0]);
Integer startM = Integer.valueOf(startDate.split("-")[1]);
Integer endY = Integer.valueOf(endDate.split("-")[0]);
Integer endM = Integer.valueOf(endDate.split("-")[1]);
//用来格式化
DecimalFormat decimalFormat = new DecimalFormat("00");
List<String> list = new ArrayList<>();
if (startY > endY){
throw new MyServiceException("日期格式不正确不对");
}
//年份相同的时候
if (startY.equals(endY)&&endM-startM>=0){
int count=startM;
while (endM-count>=0){
list.add(startY+"-"+decimalFormat.format(count));
count++;
}
}else{
int year = startY;
int month = startM;
//年份不同
while (endY-year>0){
for (int i = month; i <= 12 ; i++) {
list.add(year+"-"+decimalFormat.format(i));
}
year++;
month=1;
if (year==endY){
for (int i = 1; i <= endM; i++) {
list.add(year+"-"+decimalFormat.format(i));
}
}
}
}
return list;
}
public static void main(String[] args) {
System.out.println(getBetweenYearMonth("2020-05", "2022-10"));
}
}
测试结果如下
[2020-05, 2020-06, 2020-07, 2020-08, 2020-09, 2020-10, 2020-11, 2020-12, 2021-01, 2021-02, 2021-03, 2021-04, 2021-05, 2021-06, 2021-07, 2021-08, 2021-09, 2021-10, 2021-11, 2021-12, 2022-01, 2022-02, 2022-03, 2022-04, 2022-05, 2022-06, 2022-07, 2022-08, 2022-09, 2022-10]