题目描述
设计一个程序能计算一个日期加上若干天后是什么日期。
输入描述:
输入第一行表示样例个数m,接下来m行每行四个整数分别表示年月日和累加的天数。
输出描述:
输出m行,每行按yyyy-mm-dd的个数输出。
示例1
输入
1
2008 2 3 100
输出
2008-05-13
代码:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws NumberFormatException, IOException {
int[] months = {0,31,28,31,30,31,30,31,31,30,31,30,31};
int days =0;
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
int m = Integer.parseInt(bf.readLine());//样例数
for(int i=0; i<m; i++) {
String[] times = bf.readLine().split(" ");
int year = Integer.parseInt(times[0]);
int month = Integer.parseInt(times[1]);
int day = Integer.parseInt(times[2]);
int n = Integer.parseInt(times[3]);
months[2] = (year%400==0) || (year%4==0 && year%100!=0) ? 29 : 28;
days = (months[2] == 29) ? 366 : 365;
if(months[2] == 29) {//闰年
for(; n >= days; ) {//需要累加的天数缩短在1年之内
n -= days;
year++;
months[2] = (year%400==0) || (year%4==0 && year%100!=0) ? 29 : 28;
days = (months[2] == 29) ? 366 : 365;
}
for(; n >= months[month]; ) {//天数按月累加
n -= months[month];
month++;
if(month > 12) {
year++;
month = 1;
}
months[2] = (year%400==0) || (year%4==0 && year%100!=0) ? 29 : 28;
}
for(; n>0; n--) {//天数按天累加
day += 1;
if(day > months[month]) {
month++;
day = 1;
if(month > 12) {
year++;
month = 1;
}
months[2] = (year%400==0) || (year%4==0 && year%100!=0) ? 29 : 28;
}
}
String month1 = String.format("%02d", month);
String day1 = String.format("%02d", day);
System.out.println(year+"-"+month1+"-"+day1);
}else {//平年
for(; n >= days; ) {//需要累加的天数缩短在1年之内
n -= days;
year++;
months[2] = (year%400==0) || (year%4==0 && year%100!=0) ? 29 : 28;
days = (months[2] == 29) ? 366 : 365;
}
for(; n >= months[month]; ) {//天数按月累加
n -= months[month];
month++;
if(month > 12) {
year++;
month = 1;
}
months[2] = (year%400==0) || (year%4==0 && year%100!=0) ? 29 : 28;
}
for(; n>0; n--) {//天数按天累加
day += 1;
if(day > months[month]) {
month++;
day = 1;
if(month > 12) {
year++;
month = 1;
}
months[2] = (year%400==0) || (year%4==0 && year%100!=0) ? 29 : 28;
}
}
String month1 = String.format("%02d", month);
String day1 = String.format("%02d", day);
System.out.println(year+"-"+month1+"-"+day1);
}
}
}
}