You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将指定日期传入Java的moreTheOneYearDifference方法做年差判断?

解决日期传入及方法调用问题

要把指定的日期字符串传入moreTheOneYearDifference方法,需要先将字符串解析为Calendar对象,同时修正原代码里的静态调用冲突问题,具体实现如下:

1. 核心调整点

  • 原代码中main是静态方法,无法直接调用非静态的moreTheOneYearDifference方法,也不能访问成员变量gc,因此将方法改为静态,并在方法内部创建GregorianCalendar实例用于闰年判断。
  • 日期字符串不能直接传入方法,必须先通过SimpleDateFormat解析为Date对象,再转换为Calendar实例。
  • 原代码时间单位转换错误:getTimeInMillis()返回毫秒数,需用TimeUnit.MILLISECONDS.toDays计算天数,而非MICROSECONDS。

完整可运行代码

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.concurrent.TimeUnit;

public class DateOneYearDifferenceTest {

    public static void main(String[] args) throws Exception {
        // 定义匹配输入日期的格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        
        // 解析两个日期字符串为Date对象
        Date firstDate = dateFormat.parse("2022-08-20 10:26:44.000");
        Date secondDate = dateFormat.parse("2023-08-25 10:26:44.000");
        
        // 转换为Calendar对象
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(firstDate);
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(secondDate);
        
        // 调用方法并输出结果
        System.out.println(moreTheOneYearDifference(cal1, cal2));
    }

    public static boolean moreTheOneYearDifference(Calendar c1, Calendar c2) {
        int days = 365;
        GregorianCalendar gc = new GregorianCalendar();
        
        if (c1.before(c2) && gc.isLeapYear(c1.get(Calendar.YEAR))) {
            days += 1;
        } else if (gc.isLeapYear(c2.get(Calendar.YEAR))) {
            days += 1;
        }
        
        return TimeUnit.MILLISECONDS.toDays(Math.abs(c1.getTimeInMillis() - c2.getTimeInMillis())) >= days;
    }
}

内容的提问来源于stack exchange,提问作者Tan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 13:50:26