我想在 MPAndroidChart 图表中显示周范围。例如,在二月份,我想显示 xAxis 标签值,如 1-4、5-11、12-18、19-25、26-28。这里的 1-4 来自 2 月的第 1 周,前一个月的日期也可用。但我只需要当月的天数。但是我得到了一周中的所有日期。
public List<String> getWeeksInCurrentMonth() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
int month = cal.get(Calendar.MONTH);
List<String> weekRanges = new ArrayList<>();
while (cal.get(Calendar.MONTH) == month) {
int week = cal.get(Calendar.WEEK_OF_MONTH);
int year = cal.get(Calendar.YEAR);
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == Calendar.SUNDAY || cal.getActualMaximum(Calendar.DAY_OF_MONTH) == cal.get(Calendar.DAY_OF_MONTH)) {
int startDay = cal.get(Calendar.DAY_OF_MONTH) - (dayOfWeek - 1);
int endDay = cal.get(Calendar.DAY_OF_MONTH) + (7 - dayOfWeek);
if (endDay > cal.getActualMaximum(Calendar.DAY_OF_MONTH)) {
endDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
}
if (startDay <= endDay && startDay <= cal.getActualMaximum(Calendar.DAY_OF_MONTH)) {
weekRanges.add(String.format("%d-%d", startDay, endDay));
}
}
cal.add(Calendar.DAY_OF_MONTH, 1);
}
System.out.println(weekRanges);
return weekRanges;
}
在美国语言环境中运行时观察到的输出:
[5-11、12-18、19-25、26-28、26-28]
第一周好像少了
有人请在这里说明一下,以实现只有当前月份日期的周范围。
要获取仅包含当前月份日期的周范围,您可以修改 getWeeksInCurrentMonth() 方法中的逻辑以将当前月份考虑在内,并排除上个月或下个月的任何日期。这是一个应该实现所需行为的更新实现:
public List<String> getWeeksInCurrentMonth() {
Calendar cal = Calendar.getInstance();
int currentMonth = cal.get(Calendar.MONTH);
int currentYear = cal.get(Calendar.YEAR);
cal.set(Calendar.DAY_OF_MONTH, 1);
List<String> weekRanges = new ArrayList<>();
while (cal.get(Calendar.MONTH) == currentMonth) {
int week = cal.get(Calendar.WEEK_OF_MONTH);
int year = cal.get(Calendar.YEAR);
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
// Only consider days in the current month
if (cal.get(Calendar.MONTH) == currentMonth && cal.get(Calendar.YEAR) == currentYear) {
int startDay = cal.get(Calendar.DAY_OF_MONTH);
int endDay = startDay + (7 - dayOfWeek);
if (endDay > cal.getActualMaximum(Calendar.DAY_OF_MONTH)) {
endDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
}
weekRanges.add(String.format("%d-%d", startDay, endDay));
}
cal.add(Calendar.DAY_OF_MONTH, 7 - dayOfWeek + 1);
}
System.out.println(weekRanges);
return weekRanges;
}