java获取相邻两周的周一到周日的区间

/**
 * 获取上一周周一和周日的日期,计算区间 获取下一周周一和周日的日期,计算区间
 * 
 * @author Administrator
 *
 */
public class Test {


public static void main(String[] args) {
// System.out.println(new Test().getNextSunday());
Test test = new Test();
Calendar start = Calendar.getInstance();
start.setTime(test.getPreviousMonday());
Long startTIme = start.getTimeInMillis();



Calendar end = Calendar.getInstance();
end.setTime(test.getPreviousSunday());
Long endTime = end.getTimeInMillis();


Long oneDay = 1000 * 60 * 60 * 24l;


Long time = startTIme;
while (time <= endTime) {
Date d = new Date(time);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(df.format(d));
time += oneDay;
}
}


// 用来全局控制 上一周,本周,下一周的周数变化
private static int weeks = 0;


// 获得当前日期与本周一相差的天数
private int getMondayPlus() {
Calendar cd = Calendar.getInstance();
// 获得今天是一周的第几天,星期日是第一天,星期二是第二天
int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == 1) {
return -6;
} else {
return 2 - dayOfWeek;
}
}


// 获得上周星期一的日期
public Date getPreviousMonday() {
weeks--;
int mondayPlus = this.getMondayPlus();
GregorianCalendar currentDate = new GregorianCalendar();
currentDate.add(GregorianCalendar.DATE, mondayPlus + 7 * weeks);
Date monday = currentDate.getTime();
return monday;
}


// 获得上周星期日的日期
public Date getPreviousSunday() {
// weeks--;
int mondayPlus = this.getMondayPlus();
GregorianCalendar currentDate = new GregorianCalendar();
currentDate.add(GregorianCalendar.DATE, mondayPlus + 7 * weeks + 6);
Date monday = currentDate.getTime();
return monday;
}


// 获得本周星期一的日期
public Date getCurrentMonday() {
weeks = 0;
int mondayPlus = this.getMondayPlus();
GregorianCalendar currentDate = new GregorianCalendar();
currentDate.add(GregorianCalendar.DATE, mondayPlus);
Date monday = currentDate.getTime();
return monday;
}


// 获得下周星期一的日期
public Date getNextMonday() {
weeks++;
int mondayPlus = this.getMondayPlus();
GregorianCalendar currentDate = new GregorianCalendar();
currentDate.add(GregorianCalendar.DATE, mondayPlus + 7 * weeks);
Date monday = currentDate.getTime();
return monday;
}


// 获得下周星期一的日期
public Date getNextSunday() {
weeks++;
int mondayPlus = this.getMondayPlus();
GregorianCalendar currentDate = new GregorianCalendar();
currentDate.add(GregorianCalendar.DATE, mondayPlus + 7 * weeks + 6);
Date monday = currentDate.getTime();
return monday;
}


// 获得本周的周日的日期
public Date getSunday() {
int mondayPlus = this.getMondayPlus();
GregorianCalendar currentDate = new GregorianCalendar();
currentDate.add(GregorianCalendar.DATE, mondayPlus + 7 * weeks + 6);
Date monday = currentDate.getTime();
return monday;
}
}

内容是计算当天的上一周周一到周日以及下一周的周一到周日之间的区间范围,注意在实际使用当中,weeks参数的加减变化。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值