判断某年月日是当年的第几天

来源:互联网 发布:识汝不识丁网络剧微盘 编辑:程序博客网 时间:2024/06/06 01:11

题目描述:
输入三个整数year,month,day分别表示当前年月日,输出该天是当年的第几天

思路:
* 由于只有十二个月,所以可以枚举每个月的天数
* 需要单独考虑的是当前年份是否是闰年&&当前月份是否大月2月,如果都满足,则在总天数上+1

public class Main {    public static void main(String args[]) {        System.out.println(whichDay(2016,2,1));//为当年第31+1 = 32天        System.out.println(whichDay(2017,3,1));//为当年第31+28+1 = 60天        System.out.println(whichDay(2016,3,1));//为当年第31+29+1 = 61天    }    /**     * 由于只有十二个月,所以可以枚举每个月的天数     * 需要单独考虑的是当前年份是否是闰年&&当前月份是否大月2月,如果都满足,则在总天数上+1     * @param year     * @param month     * @param day     * @return     */    public static int whichDay(int year, int month, int day) {        final int[] monthes = new int[]{31,28,31,30,31,30,31,31,30,31,30,31};        int i = 0,num = 0;        while(i < month - 1)            num += monthes[i++];        num += day;        if(month < 3)            return num;        return num+isLeap(year);    }    /**     * 判断输入的当前年份是否是闰年,是闰年则返回1,否则返回0;     */    public static int isLeap(int year) {        if (year % 4 == 0 && year % 100 != 0)            return 1;        if (year % 400 == 0)            return 1;        else return 0;    }}

输出如下:

326061
原创粉丝点击