我希望有人可以帮助我了解Joda Time。这是代码:
DateTimeComparator comparator = DateTimeComparator.getInstance(
DateTimeFieldType.dayOfMonth(), DateTimeFieldType.year());
java.sql.Date beforeDate = new java.sql.Date(1372910400000L); // July 4 2013
java.sql.Date nowDate = new java.sql.Date(System.currentTimeMillis());
DateTime beforeDateTime = new DateTime(beforeDate);
DateTime nowDateTime = new DateTime(nowDate);
int result = comparator.compare(nowDateTime, beforeDateTime);
System.out.println(nowDate+" compared to "+beforeDate+" = "+result);
2015-03-15 compared to 2013-07-04 = -1
从Javadocs API进行比较:
返回: 如果顺序无关紧要为零,则为负值,如果lhsObj< rhsObj,否则为正值。
我做错了什么?
答案 0 :(得分:1)
看起来您将年份排除在比较之外,这使得03/15小于07/04。来自getInstance(DateTimeFieldType lowerLimit,DateTimeFieldType upperLimit)
返回具有下限和上限的DateTimeComparator。的领域 从比较中排除小于下限的幅度。 幅度大于或等于到上限的字段是 也被排除在比较之外。可以将任一限制指定为null, 这表示无限制。
答案 1 :(得分:1)
根据您当前的代码示例,您希望将null
作为DateTimeComparator
的上限,以便按日期正确比较DateTime
个对象:
DateTimeComparator.getInstance(DateTimeFieldType.dayOfMonth(), null);
这说明"比较DateTime
对象的日期,以及比这更广泛的一切,处理更精确的字段,如时间相等"。
但实际上,这根本不是你想用JodaTime做的事情。 JodaTime为不同的操作提供了许多不同的日期和时间类,如果您的目标是比较日期,则需要使用LocalDate
。它的.compareTo()
完全符合您的预期:
new LocalDate().compareTo(new LocalDate(2013,7,4)) // returns 1
请注意,java.sql.Date
仅存储日期信息,而不存储时间或时区信息。通过构造DateTime
对象,您可以人为地将时间和时区与日期相关联。 java.sql.Date
Joda-Time中的正当兄弟是LocalDate
。
当您关心日期时,请使用LocalDate
,当您关心时间时,请使用LocalTime
,当您关心某一天的时间时,请使用LocalDateTime
。这些类的共同之处在于它们代表了我们抽象的时间概念,不是历史中的瞬间。这可能看起来很奇怪,但它往往是你真正想要的。关于partials的关键概念文档详细介绍了这一点。
只有在您实际需要实时讨论时刻时才应使用DateTime
及其相关类。实际上,这并不像你想象的日期/时间繁重的代码那么常见。从Local*
类开始,看看它们是否可以满足您的使用案例。