- package com.itheima;
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- public class DaysTest {
- public static void main(String[] args) {
- try {
- InputStreamReader isr = new InputStreamReader(System.in);
- BufferedReader br = new BufferedReader(isr);
- System.out.println("请输入年月(格式:yyyymm):");//按格式输入年月
- String s = br.readLine();
- int y = Integer.parseInt(s.substring(0, 4));//截取字符串中的年
- int m = Integer.parseInt(s.substring(4, 6));//截取字符串中的月
- int num = count(y, m);
- System.out.println("距离1898年1月有" + num + "天");
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- public static int count(int year, int month) {
- int num = 0;
- int days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };//平年的月份
- int days2[] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };//闰年的月份
- if (year < 1898) { //计算在1898年之前的日期
- for (int i = year; i < 1898; i++) {
- if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {//计算年的距离时间
- num = num + 366;
- } else {
- num = num + 365;
- }
- }
- for (int j = 0; j < month - 1; j++) {//减去多余的月的距离时间
- if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
- num = num - days2[j];
- else
- num = num - days[j];
- }
- } else { //计算在1898年之后的日期
- for (int i = year; i >= 1898; i--) {
- if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {
- num = num + 366;
- } else {
- num = num + 365;
- }
- }
- for (int j = month-1; j < days.length; j++) {
- if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
- num = num - days2[j];
- else
- num = num - days[j];
- }
- }
- return num;
- }
- }
复制代码 运行结果
请输入年月(格式:yyyymm):
190501
距离1898年1月有2556天 |