计算两个日期之间的差距_学习记录

本文介绍了一种使用Java计算两个日期之间天数差的方法。通过输入两个日期的年月日,程序将判断是否为闰年,并计算从公元元年到输入日期的总天数,最后输出两个日期间的天数差。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

计算两个日期之间的差距_学习记录

package p1;

import java.util.Scanner;

/**
 * 计算两个日期的差距实现
 * @author Guozhu zhu
 * @date 2018/7/21
 * @version 1.0
 *
 */
public class Test04 {
	
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		System.out.println("================\n");
		int year01 = in.nextInt();
		int month01 = in.nextInt();
		int day01 = in.nextInt();
		System.out.println("=================\n");
		int year02 = in.nextInt();
		int month02 = in.nextInt();
		int day02 = in.nextInt();
		System.out.println("====input ok!====\n");
		int sum01 = 0;
		int sum02 = 0;
		for (int i = 0; i < year01; i++) {
			if (isLeafYear(i)) {
				sum01 += 366;
			} else {
				sum01 += 365;
			}
		}
		if (isLeafYear(year01)) {
			int[] arr = getMonthsArray(true);
			    for (int i = 0; i < month01; i++) {
				    sum01 += arr[i];
			    }
		}
		sum01 += day01;	
		for (int i = 0; i < year02; i++) {
			if (isLeafYear(i)) {
				sum02 += 366;
			} else {
				sum02 += 365;
			}
		}
		if (isLeafYear(year02)) {
			int[] arr = getMonthsArray(false);
				for (int i = 0; i < month02; i++) {
					sum02 += arr[i];
				}
	    }
	    sum02 += day02;
	    System.out.println("====output====\n");
	    System.out.println(sum02 - sum01);
	}
	
	public static boolean isLeafYear(long year) {
		if ((year%4 == 0 && year%100 != 0) || year%400 == 0) {
			return true;
		} else {
			return false;
		}
	}
	
	public static int[] getMonthsArray(boolean bool) {
		if (bool == true) {
			return new int[] {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
		} else {
			return new int[] {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
		}
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值