package com.test;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class test {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
Calendar calendar=Calendar.getInstance();
int fyear=calendar.get(Calendar.YEAR);
int fmonth=calendar.get(Calendar.MONTH);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR,fyear);
cal.set(Calendar.MONTH, fmonth);
String endDate = sdf.format(cal.getTime());
cal.add(Calendar.YEAR, -1);
cal.add(Calendar.MONTH, +1);
String startDate = sdf.format(cal.getTime());
JSONArray jsonArray = getMonthBetween(startDate,endDate);
System.out.println(jsonArray);
}
private static JSONArray getMonthBetween(String startDate, String endDate) {
JSONArray jsonArray = new JSONArray();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
Calendar min = Calendar.getInstance();
Calendar max = Calendar.getInstance();
try {
min.setTime(sdf.parse(startDate));
min.set(min.get(Calendar.YEAR),min.get(Calendar.MONTH),1);
max.setTime(sdf.parse(endDate));
max.set(max.get(Calendar.YEAR),max.get(Calendar.MONTH),2);
Calendar curr = min;
while (curr.before(max)){
JSONObject obj = new JSONObject();
obj.put("date", sdf.format(curr.getTime()));
jsonArray.add(obj);
curr.add(Calendar.MONTH, 1);
}
}catch (ParseException e){
e.printStackTrace();
}
return jsonArray;
}
}
输出:
[{"date":"2022-01"},{"date":"2022-02"},{"date":"2022-03"},{"date":"2022-04"},{"date":"2022-05"},{"date":"2022-06"},{"date":"2022-07"},{"date":"2022-08"},{"date":"2022-09"},{"date":"2022-10"},{"date":"2022-11"},{"date":"2022-12"}]