我有一个以下程序来比较两个日期。
我得到的是date1和currentTimestamp的时间戳,这里我只需要比较日期而不是时间值。但是下面的程序总是返回-1。(值)
'20:00' & '00:00' -> must be 4
如何比较日期而不考虑时间。请帮帮我。
更新:
我改为以下代码
'23:00' & '02:00' -> negative
这给我错误说“java.lang.IllegalArgumentException:找不到类型为:org.joda.time.LocalDate的即时转换器”
答案 0 :(得分:0)
要在DateTime
中joda
进行比较,您有两个选项:
DateTime
转换为LocalDate
。DateTimeComparator.getDateOnlyInstance
例如:
@Test
public void compareJodaTime() {
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS");
String today = "2017-01-20 14:51:30.091";
String tomorrow = "2017-01-21 14:51:30.091";
DateTime now = DateTime.now();
Assert.assertThat(now.toLocalDate().compareTo(DateTime.parse(today, dateTimeFormatter).toLocalDate()), Matchers.is(0));
Assert.assertThat(now.toLocalDate().compareTo(DateTime.parse(tomorrow, dateTimeFormatter).toLocalDate()), Matchers.is(-1));
Assert.assertThat(now.toLocalDate().isEqual(DateTime.parse(today, dateTimeFormatter).toLocalDate()), Matchers.is(true));
Assert.assertThat(now.toLocalDate().isBefore(DateTime.parse(tomorrow, dateTimeFormatter).toLocalDate()), Matchers.is(true));
Assert.assertThat(DateTimeComparator.getDateOnlyInstance().compare(now, DateTime.parse(today, dateTimeFormatter)), Matchers.is(0));
Assert.assertThat(DateTimeComparator.getDateOnlyInstance().compare(now, DateTime.parse(tomorrow, dateTimeFormatter)), Matchers.is(-1));
}
答案 1 :(得分:0)
这不是Joda解决方案......
使用:Apache库'commons-lang3-x.x.jar'(DateUtils)
@Test
public void testCompare() {
Date current = new Date();
Date previous = DateUtils.addHours(DateUtils.addDays(new Date(), -1),5);
assertEquals(1,DateUtils.truncatedCompareTo(current,previous,Calendar.DATE));
assertEquals(0,DateUtils.truncatedCompareTo(current,current,Calendar.DATE));
assertEquals(-1,DateUtils.truncatedCompareTo(previous,current,Calendar.DATE));
}
答案 2 :(得分:0)
您可以使用JodaTime尝试此代码:
DateTime date1 = DateTime.parse("2017-01-20 14:51:30.091", DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss.SSS"));
DateTime now = new DateTime();
int value = DateTimeComparator.getDateOnlyInstance().compare(date1 , now);