题目要求:日期格式 年-月-日 如: 2016-09-07
//Scanner读取如上格式返回String类型数据,需转化为int进行之后的运算
//判断天数需要考虑到闰年的问题
//计算天数
看了网上其他的方法,我计算天数的方法还是比较简洁的。
import java.util.Scanner;
public class Day07 {
public static void main(String[] args) {
// 1 截取字符串、转化为int,得到日期数据 年月日分别用y m d存储
Scanner sc = new Scanner(System.in);
int y, m, d;
String s, sy, sm, sd;
System.out.print("请输入日期(年-月-日):");
s = sc.nextLine();
sy = s.substring(0, 4);
sm = s.substring(5, 7);
sd = s.substring(8, 10);
y = Integer.parseInt(sy, 10);
m = Integer.parseInt(sm, 10);
d = Integer.parseInt(sd, 10);
// 2 判断是否闰年 并用 days 数组存储每月天数
boolean isLeap = false;
if ((y % 4 == 0 && y % 100 != 0) || y % 400 == 0) {
isLeap = true;
}
int[] days = new int[12];
if (isLeap) {
days = new int[] { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
} else {
days = new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
}
// 3 计算天数daysOfYear
int daysOfYear = d;
for (int i = 0; i < m - 1; i++) {
daysOfYear += days[i];
}
System.out.println("今天是" + y + "年的第" + daysOfYear + "天");
}
}