1

我有一个DateTime代表重复事件的开始。A Days(每日周期)将代表循环周期。我认为这种反复发生的事件永远不会停止。

from = "2013-06-27"  
period = 3 days
nextOccurence will be "2013-06-30", "2013-07-03", "2013-07-06", and so on.
"2013-07-03" is an occurence but "2013-07-04" isn't an occurence.

我想知道在性能方面确定 aDateTime是否发生重复事件的最佳方法是什么?从长远来看,程序需要检查“2014-07-03”或“2015-07-03”是否出现。

4

2 回答 2

1

这会在我的机器上运行所有五次检查,时间为 180 毫秒。或者大约每秒 27 次检查,您正在检查 300 年后的日期。

@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);
}
于 2013-06-26T18:10:58.900 回答
0

您始终可以在类中使用该add方法。Calendar

您可以执行以下操作 -

Date date = "2013-06-27" ; 
Calendar cal = Calendar.getInstance();  
cal.setTime(date);  
cal.add(Calendar.DATE, 3); // add 3 days  
date = cal.getTime();  

等等...

于 2013-06-26T17:56:16.937 回答