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

不想你离开。 提交于 2019-12-20 05:10:22

问题


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 recurring event will never stop.

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.

I would like to know what is the best way in term of performance to determine if a DateTime is an occurence of the recurring event? In the long term, the program will need to check if "2014-07-03" or "2015-07-03" is an occurence.


回答1:


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);
}



回答2:


You can always use the add method in the Calendar class.

You could do the following -

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

And so on...



来源:https://stackoverflow.com/questions/17327023/how-to-check-a-datetime-is-an-occurence-of-recurring-event-using-joda-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!