日是这一年的等几天Java代码_java中计算指定日期是一年的第几天的方法
Java輸入日期計(jì)算是這年的第幾天:
思路
通過年份區(qū)分出是閏年還是平年,平年 2 月 28 天,閏年 2 月 29 天;
1、3、5、7、8、10、12 月份 31 天其余月份均為 30 天;
然后將每個(gè)月的天數(shù)相加即可,注意如果輸入的是 12 月份,則是從 11 月份往前累加到1月份,1月份加的是輸入的天數(shù);
實(shí)現(xiàn)代碼: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月份的天數(shù),依次類推
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月份就加上輸入的天數(shù)
totalDays += day;
}
return totalDays;
}
}
因?yàn)橹挥?月份的天數(shù)和輸入的 day 天數(shù)是不固定的,其他月份的天數(shù)是固定的,而固定的天數(shù)是可以通過輸入的月份算出來,這樣我們就可以這樣計(jì)算:
2 月份的天數(shù) + 輸入的天數(shù) + 計(jì)算出來的固定天數(shù)
更多java知識(shí)請(qǐng)關(guān)注java基礎(chǔ)教程。
總結(jié)
以上是生活随笔為你收集整理的日是这一年的等几天Java代码_java中计算指定日期是一年的第几天的方法的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 朱茵与周星驰分手原因(朱茵周星驰分手原因
- 下一篇: airpods删除别人的配对_怎么不让别