How to check a DateTime is an occurence of recurring event using Joda Time?

前端 未结 2 1212
萌比男神i
萌比男神i 2021-01-23 12:26

I\'ve a DateTime that represent the beginning of a recurring event. A Days (daily period) will represent the recurring period. I assume that this rec

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-23 13:23

    This runs all five checks in 180 ms seconds on my machine. Or about 27-checks/second, where you are checking a date 300 years in the future.

    @Test
    public void isOccurrence() {
        long startTime = System.currentTimeMillis();
    
        assertTrue(isOccurrence(new DateMidnight(2010, 1, 10), 3, new DateTime(2010, 1, 19, 0, 0)));
        assertFalse(isOccurrence(new DateMidnight(2010, 1, 10), 3, new DateTime(2010, 1, 18, 0, 0)));
    
        assertTrue(isOccurrence(new DateMidnight(2010, 1, 10), 3, new DateTime(2310, 1, 19, 0, 0)));
        assertFalse(isOccurrence(new DateMidnight(2010, 1, 10), 3, new DateTime(2310, 1, 20, 0, 0)));
    
        assertTrue(isOccurrence(new DateMidnight(2010, 1, 10), 3, new DateTime(2010, 1, 10, 0, 0)));
    
        System.out.println("elapsed=" + (System.currentTimeMillis() - startTime));
    }
    
    public boolean isOccurrence(DateMidnight startDate, int dayIncrement, DateTime testTime) {
        DateMidnight testDateMidnight = testTime.toDateMidnight();
        while (startDate.isBefore(testDateMidnight)) {
            startDate = startDate.plusDays(dayIncrement);
        }
        return startDate.equals(testDateMidnight);
    }
    

提交回复
热议问题