代码之家  ›  专栏  ›  技术社区  ›  Teja Nandamuri

检查NSDate是否出现在特定模式下

  •  0
  • Teja Nandamuri  · 技术社区  · 7 年前

    我正在尝试创建一个日历应用程序来显示事件。

    假设在2012年1月10日创建了两个事件eventA(每周),eventB(每天)。

    因此,当用户打开当前月历时,我需要根据这些事件的重复模式确定这些事件今天是否要显示。

       NSDate * startDate
    

       NSDate *offSetEndDate = [startDate dateByAddingYears:10];
    

    我想展示utpo自其开始日期起10年的这些事件

    //Daily
            if (recurring==1) {
                NSDate *nextOccurenceDate = [startDate dateByAddingDays:1];
                BOOL eventCrossedOffSetDate = NO;
                while (eventCrossedOffSetDate == NO) {
                    [dateArr addObject:[nextOccurenceDate shortDateString]];
                    nextOccurenceDate = [nextOccurenceDate dateByAddingDays:1];
                    if (![self isDateValid:nextOccurenceDate andEndDate:offsetEndDate]) {
                        eventCrossedOffSetDate = YES;
                    }
                }
            }
    

    这将为事件生成从开始日期到当前日期的日期数组。

    这种方法只是比较两个日期。

    -(BOOL)isDateValid:(NSDate*)startDate andEndDate:(NSDate*)endDate{
    
        if ([startDate compare:endDate] == NSOrderedDescending) {
            //"startDate is later than endDate
            return NO;
        } else if ([startDate compare:endDate] == NSOrderedAscending) {
            //startDate is earlier than endDate
            return YES;
        } else {
            //dates are the same
            return YES;
    
        }
    
        return NO;
    }
    

    这当然可以完成这项工作,但对于更多的事件,这需要花费太多的时间来执行计算和返回数组。

    我能做些什么来改善这一点吗?

    1 回复  |  直到 7 年前
        1
  •  2
  •   meaning-matters    7 年前

    对于每周活动,只需检查 someDate

    let eventWeekDay  = Calendar.current.component(.weekday, from: event.startDate)
    let todayWeekDay  = Calendar.current.component(.weekday, from: Date())
    
    if todayWeekDay == eventWeekDay
    {
        // Today has the weekly event.
    }