1 回答
TA贡献1773条经验 获得超3个赞
首先,该方法针对给定日期值返回的值分别是113and 114, not-119和-120。
假设您想要根据当前(默认)时区的日期差异,您可以通过调用then将Instant值转换为。LocalDateatZonetoLocalDate
public static long daysBetweenDatesWithSign(Date d1, Date d2) {
return daysBetweenDatesWithSign(d1, d2, ZoneId.systemDefault());
}
public static long daysBetweenDatesWithSign(Date d1, Date d2, ZoneId zone) {
LocalDate instant1 = d1.toInstant().atZone(zone).toLocalDate();
LocalDate instant2 = d2.toInstant().atZone(zone).toLocalDate();
return ChronoUnit.DAYS.between(instant1, instant2);
}
测试
public static void main(String[] args) throws ParseException {
test("Nov.11,2018 11:00am", "Mar.5,2019 10:00am");
test("Nov.11,2018 11:00am", "Mar.5,2019 3:00pm");
}
public static void test(String d1, String d2) throws ParseException {
SimpleDateFormat fmt = new SimpleDateFormat("MMM.d,yyyy hh:mma");
System.out.println("[" + d1 + "] , [" + d2 + "] = " +
daysBetweenDatesWithSign(fmt.parse(d1), fmt.parse(d2)));
}
输出
[Nov.11,2018 11:00am] , [Mar.5,2019 10:00am] = 114
[Nov.11,2018 11:00am] , [Mar.5,2019 3:00pm] = 114
添加回答
举报