我有一个用户提供的日期,当然还有今天的日期。 我试图验证2天之间的差异是否至少为2周。我使用标准库完成了这个 - 但我试图用jodaTime来做这件事,我遇到了一些困难。
// BAD CODE - doesn't work
// NOTE: getUserSuppliedDate() returns an instance of java.sql.Date
// Also assume that validation prior to this call has been run that
// validates that the userSuppliedDate comes AFTER today's date - not sure if
// that is relevant in the context I'm attempting to use these particular jodaTime APIs.
DateTime jodaStartDate = new DateTime(getUserSuppliedDate());
if (Days.daysBetween(jodaStartDate, DateTime.now()).isLessThan(Days.days(14))) {
System.out.println("Bad user. You have chosen...poorly.");
}
else {
System.out.println("Well done user. You have supplied wisely.");
}
// GOOD CODE ---- ? Help =)
答案 0 :(得分:2)
您的代码会给您错误的结果,因为提供给DateTime jodaStartDate = new DateTime().withYear(2018)
.withMonthOfYear(7)
.withDayOfMonth(5); // 15 days from now
System.out.println(Days.daysBetween(jodaStartDate, DateTime.now())); // "P-15D"
System.out.println(Days.daysBetween(DateTime.now(), jodaStartDate)); // "P15D"
的日期顺序错误。由于您指定用户提供的日期在当前日期之后,您的方法将导致否定天数。
如果您切换订单,将最早的日期放在第一位,它将正常工作。
比较以下两个:
System.out.println(Weeks.weeksBetween(jodaStartDate, DateTime.now())); // "P-2W"
System.out.println(Weeks.weeksBetween(DateTime.now(), jodaStartDate)); // "P2W"
在第一种情况下,-15天的评估时间不到14天。
使用周而不是几天,您会遇到同样的问题:
BaseWindow() : m_hwnd(NULL) { }