JAVA如果根据当前日期时间得到上周一和上周末的日期时间呢?求大侠写个代码。。

2024-11-11 04:02:14
推荐回答(2个)
回答1:

public static void main(String[] args) {
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();
int dayOfWeek=calendar1.get(Calendar.DAY_OF_WEEK)-1;
int offset1=1-dayOfWeek;
int offset2=7-dayOfWeek;
calendar1.add(Calendar.DATE, offset1-7);
calendar2.add(Calendar.DATE, offset2-7);
System.out.println(calendar1.getTime());//last Monday
System.out.println(calendar2.getTime());//last Sunday
}

回答2:

Date nowdate=new Date();
int day=nowdate.getDay(); //0---6
0是周日
想方法把 0变成7
if(day==0){
day=7
}
那间隔不就是

那上周日不就是 day天前嘛
上周一不就是 day+6天前嘛
那时间总会吧
new Date(nowdate.getTime()-60*60*24*day);
new Date(nowdate.getTime()-60*60*24*(day+6));
具体间隔你想想 我没仔细想哦