因为找的算法周日会忽略,所以,在输入日期为周日的时候取前一天的日期再找出本周的日期
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String s = "2019-07-27";
Date parse = sdf.parse(s);
String[] weekDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
Calendar cal = Calendar.getInstance();
cal.setTime(parse);
int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
if (w < 0)
w = 0;
System.out.println(weekDays[w]);
String str = weekDays[w];
//如果输入的为周日
if (str.equals("星期日")){
Calendar c = Calendar.getInstance();
Date date=null;
try {
date = new SimpleDateFormat("yyyy-MM-dd").parse(s);
} catch (ParseException e) {
//e.printStackTrace();
System.out.println("解析错误");
}
c.setTime(date);
int day=c.get(Calendar.DATE);
c.set(Calendar.DATE,day-1);
String dayBefore=new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
//星期日前一天
System.out.println(str+"是星期日,他的前一天是:"+dayBefore);
Date parse1 = sdf.parse(dayBefore);
List<Date> days = dateToWeek(parse1);
for (Date d : days) {
System.out.println(sdf.format(d));
}
}else{
List<Date> days = dateToWeek(parse);
for (Date d : days) {
System.out.println(sdf.format(d));
}
}
}
@SuppressWarnings("deprecation")
public static List<Date> dateToWeek(Date mdate) {
int b = mdate.getDay();
Date fdate;
List<Date> list = new ArrayList<Date>();
Long fTime = mdate.getTime() - b * 24 * 3600000;
for (int a = 1; a <= 7; a++) {
fdate = new Date();
fdate.setTime(fTime + (a * 24 * 3600000));
list.add(a-1, fdate);
}
return list;
}