获取一个时间间隔内月份的list

原创
09/12 17:25
阅读数 109

依赖:

<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.10.5</version>
</dependency>

 


import org.joda.time.DateTime;

import java.util.ArrayList;
import java.util.List;

public class Client {
    public static void main(String[] args) {
        Long startTime = 1599148799000L;
        Long endTime=1599148799000L;
        DateTime start = new DateTime(startTime);
        DateTime end = new DateTime(endTime);

        int oneYear = start.getYear();
        int oneMonth = start.getMonthOfYear();

        int twoYear = end.getYear();
        int twoMonth = end.getMonthOfYear();


        List<String> yearMonth = getYearMonth(oneYear,twoYear,oneMonth,twoMonth);

        System.out.println(yearMonth);


    }

    private static List<String> getYearMonth(int oneYear,int twoYear ,int oneMonth,int twoMonth){
       return getYearMonth(oneYear,twoYear,oneMonth,twoMonth,"-");
    }
    private static List<String> getYearMonth(int oneYear,int twoYear ,int oneMonth,int twoMonth,String separator){
        List<String> yearMonth = new ArrayList<>();
        if(oneYear < twoYear){
            if(oneYear + 1 == twoYear){// 两个年份是间隔为1的关系
                yearMonth.addAll(getYearMonth(oneYear,separator,oneMonth,12));
                yearMonth.addAll(getYearMonth(twoYear,separator,1,twoMonth));
                return yearMonth;
            }else {
                while (oneYear < twoYear){
                    yearMonth.addAll(getYearMonth(oneYear,separator,1,12));
                    oneYear +=1;
                }
                yearMonth.addAll(getYearMonth(twoYear,separator,1,twoMonth));
            }
        }else {
            yearMonth.addAll(getYearMonth(twoYear,separator,oneMonth,twoMonth));
        }
        return yearMonth;
    }

    private static List<String> getYearMonth(int year,String separator ,int fromMonth,int toMonth){
        List<String> yearMonth = new ArrayList<>();
        for (int i = fromMonth; i <= toMonth; i++) {
            if(i< 10){
                yearMonth.add(year+separator+"0"+i);
            }else {
                yearMonth.add(year+separator+i);
            }
        }
        return yearMonth;
    }
}

结果

[2020-09]

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部