获取本年月份、本月/本周所有日期
获取本年度的十二个月份 yyyy-MM
public static List<String> getMonthByYear(){
List<String> data = new ArrayList<>();
try {
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
Date startDate = sdf.parse(year + "-01");
Date endDate = sdf.parse(year + "-12");
c.setTime(startDate);
while(c.getTime().compareTo(endDate) <= 0){
String time = sdf.format(c.getTime());
data.add(time);
c.add(Calendar.MONTH, 1);
}
} catch (ParseException e) {
e.printStackTrace();
}
return data;
}
遍历本月度的每一天 yyyy-MM-dd
public static List<String> getDayByMonth(){
List<String> data = new ArrayList<>();
try {
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH) + 1;
int dayCount = c.getActualMaximum(Calendar.DAY_OF_MONTH);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = sdf.parse(year + "-" + month + "-01");
Date endDate = sdf.parse(year + "-" + month + "-" + dayCount);
c.setTime(startDate);
while(c.getTime().compareTo(endDate) <= 0){
String time = sdf.format(c.getTime());
data.add(time);
c.add(Calendar.DATE, 1);
}
} catch (ParseException e) {
e.printStackTrace();
}
return data;
}
遍历本周的所有日期 yyyy-MM-dd
public static List<String> getDayByWeek(){
List<String> data = new ArrayList<>();
try {
String yzTime = getTimeInterval(new Date());
String[] time = yzTime.split(",");
String startTime = time[0];
String endTime = time[1];
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date dBegin = sdf.parse(startTime);
Date dEnd = sdf.parse(endTime);
List<Date> lDate = findDates(dBegin, dEnd);
for (Date date : lDate) {
data.add(sdf.format(date));
}
} catch (Exception e) {
e.printStackTrace();
}
return data;
}
public static String getTimeInterval(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
if (1 == dayWeek) {
cal.add(Calendar.DAY_OF_MONTH, -1);
}
cal.setFirstDayOfWeek(Calendar.MONDAY);
int day = cal.get(Calendar.DAY_OF_WEEK);
cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String imptimeBegin = sdf.format(cal.getTime());
cal.add(Calendar.DATE, 6);
String imptimeEnd = sdf.format(cal.getTime());
return imptimeBegin + "," + imptimeEnd;
}
public static List<Date> findDates(Date dBegin, Date dEnd) {
List<Date> lDate = new ArrayList<>();
lDate.add(dBegin);
Calendar calBegin = Calendar.getInstance();
calBegin.setTime(dBegin);
Calendar calEnd = Calendar.getInstance();
calEnd.setTime(dEnd);
while (dEnd.after(calBegin.getTime())){
calBegin.add(Calendar.DAY_OF_MONTH, 1);
lDate.add(calBegin.getTime());
}
return lDate;
}