之前找了好多没有发现有这样的操作,故今天创造出来便于记录,学习。
public static String getlastweek (String time) throws java.text.ParseException {
Calendar cal = Calendar.getInstance();
cal.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(time));
int d = 0;
if (cal.get(Calendar.DAY_OF_WEEK) == 1) {
d = -6;
} else {
d = 2 - cal.get(Calendar.DAY_OF_WEEK);
}
cal.add(Calendar.DAY_OF_WEEK, d);
// 所在周开始日期
String data1 = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
Date format = new SimpleDateFormat("yyyy-MM-dd").parse(data1);
cal.setTime(format);
int day=cal.get(Calendar.DATE);
// 此处为获得前一天的数据
// 此处修改为+1则是获取后一天
cal.set(Calendar.DATE,day-1);
String lastDay = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime());
cal.setTime(new SimpleDateFormat("yyyy-MM-dd").parse(lastDay));
int da = 0;
if (cal.get(Calendar.DAY_OF_WEEK) == 1) {
da = -6;
} else {
da = 2 - cal.get(Calendar.DAY_OF_WEEK);
}
cal.add(Calendar.DAY_OF_WEEK, da);
// 所在周开始日期
String data11 = new SimpleDateFormat("yyyy/MM/dd").format(cal.getTime());
cal.add(Calendar.DAY_OF_WEEK, 6);
// 所在周结束日期
String data2 = new SimpleDateFormat("yyyy/MM/dd").format(cal.getTime());
return data11 + "-" + data2;
}
测试
String getlastweek = getlastweek("2019-01-01");
System.out.print("获取日期前一周的时间:"+getlastweek+"\n");
打印:
获取日期前一周的时间:2018/12/24-2018/12/30