gpt4 book ai didi

java - 找出两个给定日期的天数差异

转载 作者:行者123 更新时间:2023-11-30 07:34:50 24 4
gpt4 key购买 nike

 /** Determines the difference in days between d and this Date.For example, 
* if this Date is 12/15/1997 and d is 12/14/1997, the difference is 1.
* If this Date occurs before d, the result is negative.
* @return the difference in days between d and this date.
*/

public int difference(Date d) {
int NoOfLeapYr_d = d.year/4;
int NoOfLeapYr_this = this.year/4;
int daysofthis = NoOfLeapYr_this + (this.year-1 * 365) + this.dayInYear();
int daysofd = NoOfLeapYr_d + (d.year-1 * 365) + d.dayInYear();
return daysofd - daysofthis;
}

我已经制定了这个逻辑......但它不起作用。它返回错误的答案。任何人都可以帮助逻辑吗?

最佳答案

使用 Joda 日期时间:-

@Test
public void testOneDayEarlier() {
DateTime fromDate = new DateTime(2011, 2, 12, 0, 0, 0, 0);
DateTime toDate = new DateTime(2011, 2, 13, 0, 0, 0, 0);

int days = Days.daysBetween(fromDate, toDate).getDays();
assertEquals("fromDate is one day earlier than toDate", 1, days);
}

@Test
public void testOneDayLater() {
DateTime fromDate = new DateTime(2011, 2, 13, 0, 0, 0, 0);
DateTime toDate = new DateTime(2011, 2, 12, 0, 0, 0, 0);

int days = Days.daysBetween(fromDate, toDate).getDays();
assertEquals("fromDate is one day later than toDate", -1, days);
}

@Test
public void testSameDay() {
DateTime fromDate = new DateTime(2011, 2, 13, 0, 0, 0, 0);
DateTime toDate = new DateTime(2011, 2, 13, 0, 0, 0, 0);

int days = Days.daysBetween(fromDate, toDate).getDays();
assertEquals("fromDate is the same as toDate", 0, days);
}

关于java - 找出两个给定日期的天数差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4984683/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com