首頁  >  文章  >  Java  >  java中計算指定日期是一年的第幾天的方法

java中計算指定日期是一年的第幾天的方法

尚
原創
2019-11-23 11:30:103829瀏覽

java中計算指定日期是一年的第幾天的方法

Java輸入日期計算是這年的第幾天:

想法

透過年份區分出是閏年還是平年,平年2 月28天,閏年2 月29 天;

1、3、5、7、8、10、12 月份31 天其餘月份均為30 天;

然後將每個月的天數相加即可,注意如果輸入的是12 月份,則是從11 月份往前累加到1月份,1月份加的是輸入的天數;

實現代碼:

import java.util.Scanner;

/**
 * Created by xpf on 2018/6/22 :)
 * GitHub:xinpengfei520
 * Function:
 */
public class CalculateUtils {

    /*平年二月28天*/
    private static final int DAYS_28 = 28;
    /*闰年二月29天*/
    private static final int DAYS_29 = 29;
    /*除了31天的月份其他均为30天*/
    private static final int DAYS_30 = 30;
    /*1、3、5、7、8、10、12月份31天*/
    private static final int DAYS_31 = 31;

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Please input year:");
        int year = input.nextInt();
        System.out.println("Please input month:");
        int month = input.nextInt();
        System.out.println("Please input day:");
        int day = input.nextInt();

        int daysInYear = getDaysInYear(year, month, day);
        System.out.println("daysInYear:" + daysInYear);
    }

    /**
     * get days in this year
     *
     * @param year
     * @param month
     * @param day
     * @return
     */
    public static int getDaysInYear(int year, int month, int day) {
        int totalDays = 0;

        switch (month) {
            // 12 月份加的是11月份的天数,依次类推
            case 12:
                totalDays += DAYS_30;
            case 11:
                totalDays += DAYS_31;
            case 10:
                totalDays += DAYS_30;
            case 9:
                totalDays += DAYS_31;
            case 8:
                totalDays += DAYS_31;
            case 7:
                totalDays += DAYS_30;
            case 6:
                totalDays += DAYS_31;
            case 5:
                totalDays += DAYS_30;
            case 4:
                totalDays += DAYS_31;
            case 3:
                // 判断是否是闰年
                if (((year / 4 == 0) && (year / 100 != 0)) || (year / 400 == 0)) {
                    totalDays += DAYS_29;
                } else {
                    totalDays += DAYS_28;
                }
            case 2:
                totalDays += DAYS_31;
            case 1: // 如果是1月份就加上输入的天数
                totalDays += day;
        }

        return totalDays;
    }
}

因為只有2月份的天數和輸入的day 天數是不固定的,其他月份的天數是固定的,而固定的天數是可以透過輸入的月份算出來,這樣我們就可以這樣計算:

2 月份的天數輸入的天數計算出來的固定天數

更多java知識請關注java基礎教程

以上是java中計算指定日期是一年的第幾天的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn