温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java怎么判断指定日期是一年的第几天

发布时间:2020-06-19 09:14:07 来源:亿速云 阅读:955 作者:Leah 栏目:编程语言

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判断指定日期是一年的第几天的方法,详细使用情况还需要大家自己亲自动手使用过才能领会。如果想了解更多相关内容,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI