- 获取最近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;
}
}
- 程序运行结果
[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月]