1. 程式人生 > 其它 >(類和物件)計算兩個日期之間相差天數---Java

(類和物件)計算兩個日期之間相差天數---Java

技術標籤:java程式設計程式碼練習java

1、要求:求兩個日期之間相差的天數,如1999.12.19和2021.2.13之間相差了多少天
2、實現要點:注意每個月的總天數。注意閏年二月的天數。
3、實現
(1)

public class MyDate {
    public int year;
    public int month;
    public int day;


    //1、校驗,檢測傳入引數的合法性
    //year>1949
    //1<=month<=12;
    //1<=day<=每個月的天數
    //2、如果引數不符合,應該怎麼辦
//拋異常,通知對方出錯 //嘗試修復引數 比如15個月 年加1 月加3 public MyDate(int year, int month, int day) { if (year < 1949) { RuntimeException exception = new RuntimeException("year引數錯誤"); throw exception; } if (month < 1 || month > 12) { throw
new RuntimeException("month引數錯誤"); } if (day < 1 || day > getMonthday(month, year)) { throw new RuntimeException("day引數錯誤"); } this.year = year; this.month = month; this.day = day; } //根據year和month算出該月共有多少天
public int getMonthday(int month, int year) { switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: return 31; case 4: case 6: case 9: case 11: return 30; case 2: return isLeapYear(year) ? 29 : 28; default: return -1;//前面已經限定月份的取值,但Java語法要求所有分支必須有返回值 } } public MyDate(MyDate from){ this.year=from.year; this.month=from.month; this.day=from.day; } public boolean isLeapYear(int year) { return (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0);//判斷閏年 閏年的2月有29天,非閏年的2月是28天 } @Override public String toString() { String s = String.format("%04d-%02d-%02d", year, month, day); return s; } public int DiffDays(MyDate from) { //this指向的物件和from指向的物件之間相差的天數 //要求this大於from //但引用之間無法比較大小,所以用compareTo方法進行日期的大小比較 if (this.compareTo(from) <= 0) { throw new RuntimeException("from的日期必須在當前日期之前"); } //複製from計算,以免修改別人傳入的from物件 MyDate copyFrom=new MyDate(from); int count=0; while (copyFrom.compareTo(this) <0){ //讓from向後走一天 //from.day++ System.out.println(copyFrom); copyFrom.increment();//設定月和日的進位 count++; } return count; } public void increment(){ day++; if (day<=getMonthday(month,year)){ return;//天數不大於當月總天數,不用進位 } month++; day=1; if (month<=12){ return;//月份數不大於一年總月數,不用進位 } year++; month=1; } //定義一個比較方法(from,this) //如果this<from,返回任意負數 //如果this==from,返回0 //如果this>from,返回任意正數 public int compareTo(MyDate from) { // if (this.year<from.year){ // return -1; // } // if (this.year>from.year){ // return this.year-from.year; // } //上述程式碼可直接寫成一句 if (this.year != from.year) { return this.year - from.year; } if (this.month != from.month) {//到這 說明this.year=from.year return this.month - from.month; } return this.day - from.day;//到這 說明this.month=from.month } }

(2)

public class MyDateTest {
    public static void main(String[] args) {
        MyDate from=new MyDate(2021,2,1);
        MyDate to=new MyDate(2021,2,12);

        //測試compareTo()
        System.out.println(to.compareTo(from));//正數
        System.out.println(from.compareTo(to));//負數
        System.out.println(to.compareTo(to));//0
        System.out.println(from.compareTo(from));//0

        System.out.printf("從%s到%s經過了%d天\n",from,to,to.DiffDays(from));
    }
}

4、執行結果
在這裡插入圖片描述
在這裡插入圖片描述
在這裡插入圖片描述

在這裡插入圖片描述
在這裡插入圖片描述