private Calendar calendar;
private SimpleDateFormat simpleDateFormat;
private void getWeekTime() {
simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");
timeList.clear();
//获取当前年月
int currentYear = calendar.get(Calendar.YEAR);
int currentMonth = calendar.get(Calendar.MONTH);
//设置时间
calendar.set(Calendar.MONTH, currentMonth);
calendar.set(Calendar.YEAR, currentYear);
//设置当前为这周的第2天,默认上周日为这周的第一天
calendar.set(Calendar.DAY_OF_WEEK, 2);
for (int i = 0; i < 52; i++) {
//获取你设置的时间(年,月,日),这样获取的时间就是这周一的日期了
int year1 = calendar.get(Calendar.YEAR);
int month1 = calendar.get(Calendar.MONTH) + 1;
int dayWeekStart = calendar.get(Calendar.DAY_OF_MONTH);
//获取每周周一的日期
String dayStart;
//判断获取的时间是否是本年,不是本年的话,就获取年/月/日,是本年,就获取月/日
if (year1 != currentYear) {
dayStart = year1 + "/" + month1 + "/" + dayWeekStart;
} else {
dayStart = month1 + "/" + dayWeekStart;
}
//获取周一日期的字符串,为获取其时间戳做准备
String pattern = year1 + "年" + month1 + "月" + dayWeekStart + "日";
//将日期往后加6天,也就是本周的周日
calendar.add(Calendar.DATE, 6);
//获取本周周日的日期,有获取一次年份,是为了避免一周不在同一年。
int year2 = calendar.get(Calendar.YEAR);
int month2 = calendar.get(Calendar.MONTH) + 1;
int dayWeekEnd = calendar.get(Calendar.DAY_OF_MONTH);
//获取每周周一的日期
String dayEnd = "";
if (year2 != currentYear) {
dayEnd = year2 + "/" + month2 + "/" + dayWeekEnd;
} else {
dayEnd = month2 + "/" + dayWeekEnd;
}
Date date = new Date();
try {
date = simpleDateFormat.parse(pattern);
} catch (ParseException e) {
e.printStackTrace();
}
String title;
//如果是本周的话,就返回“本周”,上周就返回“上周”
if (i == 0) {
title = "本周";
} else if (i == 1) {
title = "上周";
} else {
title = dayStart + "-" + dayEnd;
}
WeekTime weekTime = new WeekTime(date.getTime(),
//将周一的时间戳加1513526400,就是周末的时间戳了
date.getTime() + 1513526400,
String.valueOf(year2),
String.valueOf(month2),
title);
timeList.add(weekTime);
//当前时间已经是本周的周日,那么将时间往前推13天,就是上周一,进入下一个循环
calendar.add(Calendar.DATE, -13);
}
}
代码没有简化。主要是calendar.add(Calendar.DATE, num);
这个方法可以将当前时间进行推移;
网友评论