5169. 日期之間隔幾天(number-of-days-between-two-dates)

題目

請你編寫一個程序來計算兩個日期之間隔了多少天。
日期以字符串形式給出,格式爲 YYYY-MM-DD,如示例所示。

示例 1:

輸入:date1 = "2019-06-29", date2 = "2019-06-30"
輸出:1

示例 2:

輸入:date1 = "2020-01-15", date2 = "2019-12-31"
輸出:15

提示:
給定的日期是 1971 年到 2100 年之間的有效日期。

完整代碼

月份那裏要記得是小於,不是小於等於 。

for (int b = 1; b < Integer.parseInt(s1[1]); b++) {}

閏年的代碼要背熟。

year % 4 == 0 && year % 100 != 0 || year % 400 == 0

完整代碼

package weekly_contest_177;

import java.text.SimpleDateFormat;
import java.util.Date;

class Solution {
	
    public int daysBetweenDates(String date1, String date2) {
		int ss1 = nums(date1);
		int ss2 = nums(date2);
		int num = ss1 - ss2 > 0 ? ss1 - ss2 : ss2 - ss1;
		return num;
    }
    
    //計算輸入日期與1971年1月1日的差
    private int nums(String date1) {
		// string 轉數組
		String[] s2 = "1971-1-1".split("-");
		String[] s1 = date1.split("-");
		int sum = 0;
		for (int a = Integer.parseInt(s2[0]); a < Integer.parseInt(s1[0]); a++) {
			boolean yu = isyu(a);
			sum += yu ? 366 : 365;

		}
		// 月的天數相加
		boolean yuYue = isyu(Integer.parseInt(s1[0]));
		int[] bb = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
		for (int b = 1; b < Integer.parseInt(s1[1]); b++) {
			if (b == 2 && yuYue) {
				sum += 29;
			} else {
				sum += bb[b];
			}
		}
		// 日的天數相加
		sum += Integer.parseInt(s1[2]);
		return sum;
	}

    //判斷是否是閏年
	private boolean isyu(int year) {
		if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) { // 平閏年判斷算法
			return true;
		} else {
			return false;
		}
	}

	public static void main(String[] args) {
		Solution s = new Solution();
		// String date1 = "2020-01-15", date2 = "2019-12-31";
		// String date1 = "2019-06-29", date2 = "2019-06-30";
		// String date1 = "2080-08-08", date2 = "2009-08-18";
		String date1 = "2074-09-12", date2 = "1983-01-08";
		int i = s.daysBetweenDates(date1, date2);
		System.out.println("i=" + i);
		System.out.println(i == s.daysBetweenDates2(date1, date2));
	}
	
	public int daysBetweenDates2(String date1, String date2) {
		int num = 0;
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date d1 = sdf.parse(date1);
			Date d2 = sdf.parse(date2);
			long time = d1.getTime() - d2.getTime();
			time = time < 0 ? -time : time;
			num = (int) (time / 1000 / 60 / 60 / 24);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return num;
	}
    
}

閏年

閏年是公曆中的名詞。閏年分爲普通閏年和世紀閏年。
普通閏年:公曆年份是4的倍數的,且不是100的倍數,爲閏年。(如2004年就是閏年);
世紀閏年:公曆年份是整百數的,必須是400的倍數纔是世紀閏年(如1900年不是世紀閏年,2000年是世紀閏年);
閏年(Leap Year)是爲了彌補因人爲曆法規定造成的年度天數與地球實際公轉週期的時間差而設立的。補上時間差的年份爲閏年。閏年共有366天(1-12月分別爲31天,29天,31天,30天,31天,30天,31天,31天,30天,31天,30天,31天)。
凡陽曆中有閏日(二月爲二十九日)的年;閏餘(歲餘置閏。陰曆每年與迴歸年相比所差的時日);注意閏年(公曆中名詞)和閏月(農曆中名詞)並沒有直接的關聯,公曆中只分閏年和平年,平年有365天,而閏年有366天(2月中多一天);平年中也可能有閏月(如2017年是平年,農曆有閏月,閏6月)。

參考資料

閏年
5169. 日期之間隔幾天

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章