public static int daysTo20200301(String dateStr) {
    SimpleDateFormat sdf = new SimpleDateFormat('yyyy-MM-dd');
    Calendar cal = Calendar.getInstance();
    int days = 0;
    try {
        Date date = sdf.parse(dateStr);
        cal.setTime(date);
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        int day = cal.get(Calendar.DAY_OF_MONTH);
        if (year > 2020 || (year == 2020 && month > 3) || (year == 2020 && month == 3 && day > 1)) {
            return -1; // 输入日期不能大于 2020 年 3 月 1 日
        }
        if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
            // 闰年
            int[] daysOfMonth = {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335};
            days += daysOfMonth[month - 1] + day - 1;
            if (month > 2) {
                days++; // 2 月 29 日
            }
        } else {
            // 平年
            int[] daysOfMonth = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
            days += daysOfMonth[month - 1] + day - 1;
        }
        days += 365 * (2020 - year); // 年数差
        for (int i = year; i < 2020; i++) {
            if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {
                days++; // 闰年多一天
            }
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return days;
}

// 测试
public static void main(String[] args) {
    String dateStr = '2019-12-31';
    int days = daysTo20200301(dateStr);
    if (days == -1) {
        System.out.println('输入日期不能大于 2020 年 3 月 1 日');
    } else {
        System.out.println('本系统已经陪您度过了' + days + '天');
    }
}

该代码使用 Java 中的 CalendarSimpleDateFormat 类来实现日期计算。首先,将输入的日期字符串解析为 Date 对象,然后使用 Calendar 类获取日期的年、月、日信息,并根据闰年和平年判断天数。最后,计算输入日期到 2020 年 3 月 1 日的天数。

代码功能:

  1. 解析输入日期字符串,并获取年、月、日信息。
  2. 判断输入日期是否大于 2020 年 3 月 1 日,如果大于则返回 -1。
  3. 根据闰年和平年规则计算输入日期到当年 3 月 1 日的天数。
  4. 计算输入日期到 2020 年的年数差,并根据闰年规则计算年数差对应的总天数。
  5. 将以上计算结果相加,得到输入日期到 2020 年 3 月 1 日的总天数。
  6. 输出结果,显示 '本系统已经陪您度过了 * 天'。

代码使用示例:

输入日期为 '2019-12-31',则输出结果为 '本系统已经陪您度过了 92 天'。

Java 计算日期到 2020 年 3 月 1 日的天数

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

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