AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 79591696
Accepted
Rogers
Rogers
Asked: 2025-04-25 10:09:54 +0800 CST2025-04-25 10:09:54 +0800 CST 2025-04-25 10:09:54 +0800 CST

Calcular datas de ocorrência de EKRecurrenceRule

  • 772

Dado um EKRecurrenceRule, uma data de início e um intervalo de datas, como obter uma lista de datas de ocorrência que se enquadram nesse intervalo?

ekevent
  • 2 2 respostas
  • 21 Views

2 respostas

  • Voted
  1. Best Answer
    Sidik Asruri
    2025-04-25T10:15:59+08:002025-04-25T10:15:59+08:00
    Here’s a general approach:
    
    Step-by-step (in Swift):
    
    1. Create an EKEvent with a recurrence rule.
    
    
    2. Use EKEventStore to fetch events in a date range, which will include the recurring ones.
    
    
    
    Example in Swift:
    
    import EventKit
    
    let store = EKEventStore()
    store.requestAccess(to: .event) { (granted, error) in
        if granted {
            let calendars = store.calendars(for: .event)
            let startDate = Date()
            let endDate = Calendar.current.date(byAdding: .year, value: 1, to: startDate)!
    
            let predicate = store.predicateForEvents(withStart: startDate, end: endDate, calendars: calendars)
    
            let events = store.events(matching: predicate)
            
            let recurringEvents = events.filter { $0.recurrenceRules != nil }
            
            for event in recurringEvents {
                print("Event:
    
    
    • 1
  2. Rogers
    2025-04-25T10:09:54+08:002025-04-25T10:09:54+08:00

    Foi isso que eu criei. Não está completo (algumas das regras mais esotéricas de mês/ano precisam de algum ajuste), mas é um começo e bom o suficiente para dados de calendário mais simples.

    @interface EKRecurrenceRule ()
    -(NSArray<NSDate*>*)occurrencesForEventStart:(NSDate*)eventStart rangeStart:(NSDate*)rangeStart rangeEnd:(NSDate*)rangeEnd;
    @end
    
    @implementation EKRecurrenceRule ()
    -(NSArray<NSDate*>*)occurrencesForEventStart:(NSDate*)eventStart rangeStart:(NSDate*)rangeStart rangeEnd:(NSDate*)rangeEnd
    {
        static NSCalendar *calendar = [NSCalendar.alloc initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
        //  daily every N days
        //  weekly every N weeks (on days)
        //  monthly every N months (on days of the month)
        //  monthly every N months (on the 1st/2nd/3rd/4th/5th/last day/weekday/weekend day/sun-mon-tue etc of the month)
        //  yearly every N years (in Jan/Feb/Mar etc) (on the 1st/2nd/3rd/4th/5th/last day/weekday/weekend day/sun-mon-tue etc of the month)
    
        //  always fix H:M:S
    
        NSCalendarUnit hms = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    
        //  make an array of NSDateComponents's for eg 1st and 3rd Sunday in the month
    
        NSMutableArray<NSDateComponents*> *componentss = NSMutableArray.array;
        switch( self.frequency )
        {
            case EKRecurrenceFrequencyDaily:
                [componentss addObject:[calendar components:hms fromDate:eventStart]];
                break;
    
            case EKRecurrenceFrequencyWeekly:
                if( self.daysOfTheWeek )
                    for( EKRecurrenceDayOfWeek *dow in self.daysOfTheWeek )
                    {
                        NSDateComponents *dc = [calendar components:hms fromDate:eventStart];
                        dc.weekday = dow.dayOfTheWeek;
                        [componentss addObject:dc];
                    }
                else
                    [componentss addObject:[calendar components:hms|NSCalendarUnitWeekday fromDate:eventStart]];
                break;
    
            case EKRecurrenceFrequencyMonthly:
                if( self.daysOfTheMonth )
                {
                    for( NSNUmber *day in self.daysOfTheMonth )
                    {
                        NSDateComponents *dc = [calendar components:hms|NSCalendarUnitDay fromDate:eventStart];
                        dc.day = day.integerValue;
                        [componentss addObject:dc];
                    }
                }
                else if( self.daysOfTheWeek )
                {
                    for( EKRecurrenceDayOfWeek *dow in self.daysOfTheWeek )
                    {
                        NSDateComponents *dc = [calendar components:hms|NSCalendarUnitWeekday fromDate:eventStart];
                        dc.weekday = dow.dayOfTheWeek;
                        dc.weekdayOrdinal = dow.weekNumber;
                        [componentss addObject:dc];
                    }];
                }
                else
                    [componentss addObject:[calendar components:hms|NSCalendarUnitDay fromDate:eventStart]];
                break;
    
            case EKRecurrenceFrequencyYearly:
                [componentss addObject:[calendar components:hms|NSCalendarUnitDay|NSCalendarUnitMonth fromDate:eventStart]];
                break;
        }
    
        NSMutableArray<NSDate*> *occurrences = NSMutableArray.array;
        __block NSInteger interval = 1;
    
        //  enumerateDates seems to be buggy depending on this date, eg setting it to 1 second prior to the eventStart skips the 2nd expected occurrence
        //  I set it to eventStart - 1 day + 1 second
    
        NSDate *afterDate = [NSDate dateWithTimeInterval:-86400+1 sinceDate:eventStart];
        for( NSDateComponents *components in componentss )
        {
            [calendar enumerateDatesStartingAfterDate:afterDate
                                    matchingComponents:components
                                               options:NSCalendarMatchStrictly
                                            usingBlock:^(NSDate *date, BOOL, BOOL *stop)
             {
                 // reached end?
    
                 if( [date compare:rangeEnd]==NSOrderedDescending
                    || (self.recurrenceEnd && [date compare:self.recurrenceEnd.endDate]==NSOrderedDescending) )
                 {
                     *stop = YES;
                     return;
                 }
    
                 // interval?
    
                 if( interval==1 )
                 {
                     // include this one, but only if after rangeStart
    
                     if( [rangeStart compare:date]==NSOrderedAscending )
                         [occurrences addObject:date];
    
                     // start counting down the interval
    
                     interval = self.interval;
                 }
                 else
                 {
                     // don't include this one, and count down the interval
    
                     interval--;
                 }
             }];
        }];
    
        //  sort dates and limit by number of occurrences
    
        [occurrences sortUsingSelector:@selector(compare:)];
    
        if( self.recurrenceEnd.occurrenceCount )
            [occurrences removeObjectsInRange:NSMakeRange(self.recurrenceEnd.occurrenceCount,
                                                          occurrences.count-self.recurrenceEnd.occurrenceCount)];
        return occurrences;
    }
    
    @end
    
    • 0

relate perguntas

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Reformatar números, inserindo separadores em posições fixas

    • 6 respostas
  • Marko Smith

    Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não?

    • 2 respostas
  • Marko Smith

    Problema com extensão desinstalada automaticamente do VScode (tema Material)

    • 2 respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Martin Hope
    Fantastic Mr Fox Somente o tipo copiável não é aceito na implementação std::vector do MSVC 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant Encontre o próximo dia da semana usando o cronógrafo 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor O inicializador de membro do construtor pode incluir a inicialização de outro membro? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul O C++20 mudou para permitir a conversão de `type(&)[N]` de matriz de limites conhecidos para `type(&)[]` de matriz de limites desconhecidos? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann Como/por que {2,3,10} e {x,3,10} com x=2 são ordenados de forma diferente? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve