Skip to content

Instantly share code, notes, and snippets.

@wyon
Created September 21, 2017 07:00
Show Gist options
  • Save wyon/7d6cde29ec665d6e09dbc0a1eea0a7e5 to your computer and use it in GitHub Desktop.
Save wyon/7d6cde29ec665d6e09dbc0a1eea0a7e5 to your computer and use it in GitHub Desktop.
获取一段时间之间,所有的周
public static List<WeekBean> parseNatureWeek(long startMs, long endMs) {
if (startMs > endMs) {
return Collections.emptyList();
}
Calendar calendar = Calendar.getInstance();
// end date
calendar.setTimeInMillis(endMs);
clearTime(calendar);
endMs = calendar.getTimeInMillis();
// config week
calendar.setFirstDayOfWeek(Calendar.MONDAY);
calendar.setMinimalDaysInFirstWeek(7);
// start date week info
calendar.clear();
calendar.setTimeInMillis(startMs);
// move to first day in week
int days = calendar.get(Calendar.DAY_OF_WEEK) - calendar.getFirstDayOfWeek();
if (days != 0) {
if (days < 0) {
days += 7;
}
calendar.add(Calendar.DAY_OF_WEEK, -days);
}
clearTime(calendar);
// not 00:00:00, use 00:01:01
calendar.set(Calendar.MINUTE, 1);
calendar.set(Calendar.SECOND, 1);
// gen weekbean list
long start;
long end;
final List<WeekBean> resultList = new ArrayList<>();
do {
start = calendar.getTimeInMillis();
calendar.add(Calendar.DAY_OF_WEEK, 6);
end = calendar.getTimeInMillis();
resultList.add(new WeekBean(start, end));
// update startMs -> endWeekDate
clearTime(calendar);
startMs = calendar.getTimeInMillis();
//
if (startMs >= endMs) {
break;
}
calendar.clear();
calendar.setTimeInMillis(end);
calendar.add(Calendar.DAY_OF_WEEK, 1); // next monday
} while (true);
return resultList;
}
private static void clearTime(Calendar calendar) {
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
}
private static class WeekBean {
public static final String FORMAT = "MM月dd日";
public final long startDateMs;
public final long endDateMs;
private String mToString;
public WeekBean(long startDateMs, long endDateMs) {
this.startDateMs = startDateMs;
this.endDateMs = endDateMs;
}
@Override
public String toString() {
if (mToString == null) {
mToString = DateTimeUtil.longToDateStr(startDateMs, FORMAT) +
" — " +
DateTimeUtil.longToDateStr(endDateMs, FORMAT);
}
return mToString;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment