获取最近6个月时间段

  1. 获取最近6个月时间段;
package org.dsg.jdk;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;

public class CalendarDemo {
    public static void main(String[] args) {
        System.out.println(getRecentlySixMonths(2022));
        System.out.println(getRecentlySixMonths(2021));
    }

    /**
     * 获得最近6个月时间段,月份格式1-2月,1-3月,...,1-12月
     * @param year 输入年份
     * @return 当前年返回最近6个月时间段,往年返回11个月的时间段
     */
    private static List<String> getRecentlySixMonths(int year) {
        List<String> dataList = new ArrayList<>();
        int currentYear = LocalDateTime.now().getYear();
        if (year == currentYear) {
            //获取日历对象
            Calendar calendar = Calendar.getInstance();
            //重新设置日历月份字段,默认从0开始,把当前月添加处理
            calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + 1);
            for (int i=0;i<6;i++) {
                calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1);
                dataList.add((calendar.get(Calendar.MONTH) == 0?year-1:year) + ":1-"
                    + (calendar.get(Calendar.MONTH) == 0?(calendar.get(Calendar.MONTH)-1)
                    :calendar.get(Calendar.MONTH)) + "月");
            }
            //调整顺序为升序
            Collections.reverse(dataList);
        } else {
            for (int i=2;i<=12;i++) {
                dataList.add(year + ":1-" + i + "月");
            }
        }
        //3.返回时间段列表
        return dataList;
    }
}
  1. 程序运行结果

[2022:1-4月, 2022:1-5月, 2022:1-6月, 2022:1-7月, 2022:1-8月, 2022:1-9月]
[2021:1-2月, 2021:1-3月, 2021:1-4月, 2021:1-5月, 2021:1-6月, 2021:1-7月, 2021:1-8月, 2021:1-9月, 2021:1-10月, 2021:1-11月, 2021:1-12月]

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

快乐江小鱼

知识创造财富,余额还是小数

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值