java 输入一个日期为开始,用1周为单位,分别输出7天的第一天和最后一天的日期。直到本年末为止。

2020-06-13 教育 93阅读
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Scanner;
public class A {
public static void main(String[] args) {

System.out.print("请输入日期:: ");

String[] input = new Scanner(System.in).nextLine().trim().split("-");

int year = Integer.parseInt(input[0]);
int month = Integer.parseInt(input[1]);
int date = Integer.parseInt(input[2]);

Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month - 1);
cal.set(Calendar.DATE, date);

final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

int count = 0;
int weekCount = 1;
System.out.println("开始时间\t结束时间\t\t 第几周");
while(cal.get(Calendar.YEAR) == year){
if(count == 7){
System.out.print(sdf.format(cal.getTime())+ "\t");
System.out.println("\t" + weekCount++);
count=-1;
}else if(count == 0){
System.out.print(sdf.format(cal.getTime())+ "\t");
}

cal.add(Calendar.DATE, 1);
count++;
}

if(count != 7){
cal.add(Calendar.DATE, -1);
System.out.println(sdf.format(cal.getTime()) + "\t\t" + weekCount);
}
}
}
--------------测试
请输入日期: 2011-10-1
开始时间 结束时间 第几周
2011-10-01 2011-10-08 1
2011-10-09 2011-10-16 2
2011-10-17 2011-10-24 3
2011-10-25 2011-11-01 4
2011-11-02 2011-11-09 5
2011-11-10 2011-11-17 6
2011-11-18 2011-11-25 7
2011-11-26 2011-12-03 8
2011-12-04 2011-12-11 9
2011-12-12 2011-12-19 10
2011-12-20 2011-12-27 11
2011-12-28 2011-12-31 12
声明:你问我答网所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流。若您的权利被侵害,请联系fangmu6661024@163.com