如何将指定日期传入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
相关产品推荐
相关产品推荐

