【问题标题】:How to check a DateTime is an occurence of recurring event using Joda Time?如何使用 Joda Time 检查 DateTime 是否发生重复事件?
【发布时间】:2013-06-26 17:46:44
【问题描述】:

我有一个DateTime,它代表一个重复事件的开始。 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.

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

【问题讨论】:

    标签: java performance time jodatime


    【解决方案1】:

    这会在 180 ms 秒内在我的机器上运行所有五项检查。或者大约 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);
    }
    

    【讨论】:

    • 你让我免于过早的优化!我一直在考虑重新设计我的课程,但我现在知道这不值得。谢谢你的事实!
    • @Keith 顺便说一句,Joda-Time 中所有与“午夜”相关的类和方法都已弃用。请改用较新的DateTime::withTimeAtStartOfDay 方法。但是这个问题不影响这个Answer的逻辑。或者LocalDate 在这里合适吗?
    【解决方案2】:

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

    您可以执行以下操作 -

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

    等等……

    【讨论】:

    • 如果我要检查 2015 年或 2017 年的日期,会出现很多循环。这会产生性能问题还是可以忽略不计?
    • 你不能做任何比这更多的事情。有DateUtils,但它不允许您定义 3 天,而是定义周或月,这会给出一个迭代器。
    • 我看到这是唯一可能的解决方案。在接受您的回答之前,我将等待更多反馈。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2015-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2011-02-11
    • 1970-01-01
    • 2013-05-05
    相关资源
    最近更新 更多