有时候需要获取一个月的信息去展示数据,提供一些方法获取 private static List<WeekDay> getWeekDay() { Calendar calendar = Calendar.getInstance(); // 获取本周的第一天 int firstDayOfWeek = calendar.getFirstDayOfWeek(); List<WeekDay> list = new ArrayList<>(); for (int i = 0; i < 7; i++) { //Calendar.ERA 表示纪元 //Calendar.MONTH 表示月 //Calendar.DAY_OF_WEEK 表示星期几 //Calendar.AM_PM 上午还是下午 calendar.set(Calendar.DAY_OF_WEEK, firstDayOfWeek + i); WeekDay weekDay = new WeekDay(); // 获取星期的显示名称,例如:周一、星期一、Monday等等 //Calendar.SHORT得到的是诸如“周日”的名称,Calendar.LONG得到的是诸如“星期日”的名称 //Locale.CHINA(中文)、Locale.ENGLISH(英文)等等。也可以使用Locale.getDefault()获取默认语言环境 weekDay.week = calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.ENGLISH); weekDay.month = new SimpleDateFormat("MM").format(calendar.getTime()); weekDay.day = new SimpleDateFormat("dd").format(calendar.getTime()); list.add(weekDay); } return list; } private static List<WeekDay> getMonthDay() { Calendar calendar = Calendar.getInstance(); //设置某一年 calendar.set(Calendar.YEAR, 2023); //设置为某一个月 calendar.set(Calendar.MONTH, getMonth() - 1); //本月第一天 int firstDayOfMonth = calendar.getActualMinimum(Calendar.DAY_OF_MONTH); //本月最后一天 int lastDayOfMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); List<WeekDay> list = new ArrayList<>(); for (int i = 0; i < lastDayOfMonth; i++) { calendar.set(Calendar.DAY_OF_MONTH, firstDayOfMonth + i); WeekDay weekDay = new WeekDay(); // 获取星期的显示名称,例如:周一、星期一、Monday等等 weekDay.week = calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault()); weekDay.month = new SimpleDateFormat("MM").format(calendar.getTime()); weekDay.day = new SimpleDateFormat("dd").format(calendar.getTime()); list.add(weekDay); } return list; } //获取当前月 public static int getMonth() { Calendar cd = Calendar.getInstance(); //显示当前月份需要+1,因为是从0 开始计算的,使用时需要 -1 ,不然就是下个月份的日期了 return cd.get(Calendar.MONTH) + 1; } private static class WeekDay { //星期的显示名称 public String week; //对应的日期 public String month; public String day; @Override public String toString() { return "WeekDay{" + "week='" + week + '\'' + ", month='" + month + '\'' + ", day='" + day + '\'' + '}'; } }
打印一下:
List<WeekDay> list = getMonthDay(); for (WeekDay weekday : list) { Log.e("--------------->", weekday.toString()); }