给出年份,周次获取给定年份的给定周次的开始日期和结束日期
Java代码
public static String[] getDate(int year,int week){
// Calendar ca = Calendar.getInstance();
// ca.set(Calendar.WEEK_OF_YEAR, 47);
//year,week,
int year1, year2, month1, month2, day1, day2, sum = 0;
int[] days = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; //闰年
int i;
// Scanner scan = new Scanner(System.in);
// System.out.print("年:");
// year = scan.nextInt();
// System.out.print("周次:");
// week = ((Scanner) scan).nextInt();
if (year < 0) {
System.out.println("年份错误,必须大于等于0");
return null; }
if (week < 1 || week > 54) {
System.out.println("周次错误,必须位于 1 .. 53 之间");
return null;
}
sum += 7 * (week - 1);
//修正总天数
Calendar c = Calendar.getInstance();
c.set(year, 0, 1);
switch (c.get(Calendar.DAY_OF_WEEK))
{
case Calendar.TUESDAY:
{
sum -= 1;
break;
}
case Calendar.WEDNESDAY:
{
sum -= 2;
break;
}
case Calendar.THURSDAY:
{
sum -= 3;
break; }
case Calendar.FRIDAY:
{
sum -= 4;
break;
}
case Calendar.SATURDAY:
{
sum -= 5;
break;
}
case Calendar.SUNDAY:
{
sum -= 6;
break;
}
default:
break;
}
if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))
{ days[1] = 29; }
for (i = 0; i < days.length; i++) {
if (sum >= days[i]) {
sum -= days[i];
}
else {
break;
} }
year1 = year;
month1= i + 1;
day1 = sum + 1; //修改开始日期
if (day1 < 1) {
day1 += days[11];
month1 = 12;
year1--; }
year2 = year1;
month2 = month1;
day2 = day1 + 6;
if (day2 > days[month1 - 1]) {
day2 -= days[month1 - 1];
month2++;
if (month2 > 12) {
month2 = 1;
year2++;
}
}
String[] sarr = new String[2];
String ma,da,mb,db;
if(month1<10){
ma = "0"+month1;
}else{
ma = month1+"";
}
if(month2<10){
mb = "0"+month2;
}else{
mb = month2+"";
}
if(day1<10){
da = "0"+day1;
}else{
da = day1+"";
}
if(day2<10){
db = "0"+day2;
}else{
db = day2+"";
}
sarr[0] = year1+"-"+ma+"-"+da+" 00:00:00";
sarr[1] = year2+"-"+mb+"-"+db+" 23:59:59";
System.out.printf("%d年第%d周 : %d年%d月%d日 ~ %d年%d月%d日", year, week, year1, month1, day1, year2, month2, day2);
return sarr;
}