Compare dates ignoring milliseconds?

前端 未结 10 1292
北海茫月
北海茫月 2021-02-08 06:36

Is there a way to compare two calendar objects, but ignore milliseconds?

I have written a test case that compared two calendar objects, but there is a p

10条回答
  •  遇见更好的自我
    2021-02-08 07:17

    If you are on Java 8, you can use the Java Time API, specifically Calendar::toInstant(), followed by Instant::truncatedTo(). Specify the granularity of truncation using ChronoUnit enum.

    myCalendar.toInstant().truncatedTo( ChronoUnit.SECONDS )  // Lop off any fractional second.
    

    Example.

        Calendar oneMonthIsh = Calendar.getInstance();
        oneMonthIsh.add(Calendar.MONTH, -1);
        oneMonthIsh.add(Calendar.MINUTE, 1);
    
        assertNotEquals(oneMonthIsh.toInstant(), getExpectedOneMonthDateFromCurrentDate());
        assertEquals(oneMonthIsh.toInstant().truncatedTo(ChronoUnit.DAYS),getExpectedOneMonthDateFromCurrentDate().toInstant()
        .truncatedTo(ChronoUnit.DAYS));
    

提交回复
热议问题