方法
private List getFormatDate(String type) {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
List list = new ArrayList<>();
if ("day".equals(type)) {
list.add(sdf.format(calendar.getTime()));
} else if ("month".equals(type)) {
int index = calendar.get(Calendar.DAY_OF_MONTH);
for (int i = 0; i < index; i++) {
list.add(sdf.format(calendar.getTime()));
calendar.add(Calendar.DAY_OF_MONTH, -1);
}
} else {
int index = calendar.get(Calendar.DAY_OF_WEEK) == 1 ? 7 : calendar.get(Calendar.DAY_OF_WEEK) - 1;
for (int i = 0; i < index; i++) {
list.add(sdf.format(calendar.getTime()));
calendar.add(Calendar.DAY_OF_MONTH, -1);
}
}
// 日期翻转,本来是从大到小,翻转成从小到大
Collections.reverse(list);
return list;
}
测试
// Main方法测试
public static void main(String[] args) {
// 获取本日日期数组
List days = getFormatDate("day");
System.out.println(JSONObject.toJSonString(days));
// 获取本周日期数组
List weeks = getFormatDate("week");
System.out.println(JSONObject.toJSonString(weeks));
// 获取本月日期数组
List months = getFormatDate("month");
System.out.println(JSONObject.toJSonString(months));
// 默认
List defs = getFormatDate("abc");
System.out.println(JSONObject.toJSonString(defs));
}
// 如果你想改成其他日期做测试,只需要替换方法的第一行为:
Calendar calendar = DateUtil.toCalendar(DateUtil.getDateOfStr("2022-01-01"));
// 测试结果
["2022-01-12"]
["2022-01-10","2022-01-11","2022-01-12"]
["2022-01-01","2022-01-02","2022-01-03","2022-01-04","2022-01-05","2022-01-06","2022-01-07","2022-01-08","2022-01-09","2022-01-10","2022-01-11","2022-01-12"]
["2022-01-10","2022-01-11","2022-01-12"]