如何使用Joda Time检查DateTime是否为重复发生的事件? [英] How to check a DateTime is an occurence of recurring event using Joda Time?

查看:57
本文介绍了如何使用Joda Time检查DateTime是否为重复发生的事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我想知道从性能上确定DateTime是否发生重复事件的最佳方法是什么?从长远来看,该程序将需要检查是否出现了"2014-07-03"或"2015-07-03".

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.

推荐答案

这将在我的计算机上在180毫秒内运行所有五次检查.大约每秒27次检查,即您要检查未来300年的日期.

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

这篇关于如何使用Joda Time检查DateTime是否为重复发生的事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆