import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // 输入年、月、日
        System.out.print('请输入年:');
        int year = scanner.nextInt();
        System.out.print('请输入月:');
        int month = scanner.nextInt();
        System.out.print('请输入日:');
        int day = scanner.nextInt();

        // 判断是否是闰年
        boolean isLeapYear = false;
        if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
            isLeapYear = true;
        }

        // 计算当月之前的天数
        int daysBeforeMonth = 0;
        switch (month - 1) {
            case 11:
                daysBeforeMonth += 30;
            case 10:
                daysBeforeMonth += 31;
            case 9:
                daysBeforeMonth += 30;
            case 8:
                daysBeforeMonth += 31;
            case 7:
                daysBeforeMonth += 31;
            case 6:
                daysBeforeMonth += 30;
            case 5:
                daysBeforeMonth += 31;
            case 4:
                daysBeforeMonth += 30;
            case 3:
                daysBeforeMonth += 31;
            case 2:
                if (isLeapYear) {
                    daysBeforeMonth += 29;
                } else {
                    daysBeforeMonth += 28;
                }
            case 1:
                daysBeforeMonth += 31;
        }

        // 计算当天是当年的第几天
        int dayOfYear = daysBeforeMonth + day;

        // 输出结果
        System.out.println(year + '年' + month + '月' + day + '日是当年的第' + dayOfYear + '天。');
    }
}

本代码首先使用 Scanner 类从用户获取输入的年、月、日。然后,它判断输入的年份是否是闰年,并根据月份计算当月之前的天数。最后,将当月之前的天数加上输入的日期,即可得到当天是当年的第几天。

本示例代码简单易懂,可以帮助您快速理解如何使用 Java 代码计算日期是当年的第几天。您可以根据自己的需要进行修改和扩展。

Java 计算日期是当年的第几天

原文地址: https://www.cveoy.top/t/topic/oUMK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录