Search code examples
xcodensdatenscalendarnsdatecomponentsekeventkit

Using NSDate and NSDate components to calc time between 2 dates (Max 6 days, 23 hrs, 59 min, 59sec in the future)


UPDATE: This is the working example.

First we create a class to hold weekday, hr, min, and sec:

myClass.h

#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>

@interface myClass : NSObject {
NSString *weekday;
NSInteger hour;
NSInteger minute;
NSInteger second;
}

@property (nonatomic, strong) NSString *weekday;
@property (nonatomic, assign) NSInteger hour;
@property (nonatomic, assign) NSInteger minute;
@property (nonatomic, assign) NSInteger second;

@end

myClass.m

#import "myClass.h"

@implementation myClass
@synthesize weekday, hour, minute, second;

@end

Next, we need to create an instance of myClass that holds our date info.

Add this to ViewController.h:

@property (nonatomic, strong) NSMutableArray *myArray;

This code goes in ViewController.m wherever you'd like:

myArray = [[NSMutableArray alloc] init];

//Setup an instance of myClass 
myClass *c = [[myClass alloc] init];
[c setWeekday:@"Monday"];
[c setHour:13];
[c setMinute:0];
[c setSecond:0];

[myArray addObject:c];

Next we need to figure out how far in the future our event is. Thanks to rdelmar we have the code to do this, his answer is below

//Create a func that returns an NSDate. It requires that the Weekday, HR, Min and Secs are passed into it.
-(NSDate *)getNextDateOn:(NSString *)weekday atHour:(NSInteger)hour minute:(NSInteger)mins second:(NSInteger)secs {

//Setup an array of weekdays to compare to the imported (NSString *)weekday 
NSArray *array = [NSArray arrayWithObjects:@"Sunday",@"Monday",@"Tuesday",@"Wednesday",@"Thursday",@"Friday",@"Saturday",nil];
NSInteger weekdayNumber = [array indexOfObject:[weekday capitalizedString]] + 1;

//This code finds how many days in the future the imported (NSString *)weekday is
NSDate *now = [NSDate date];
NSCalendar *cal = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents *nowComps = [cal components:NSWeekdayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit fromDate:now];
NSInteger daysForward = (weekdayNumber - nowComps.weekday + 7) % 7;

//Lastly, create an NSDate called eventDate that consists of the 
NSDateComponents *eventComps = [[NSDateComponents alloc] init];
[eventComps setDay:daysForward];
[eventComps setHour: hour - nowComps.hour];
[eventComps setMinute: mins - nowComps.minute];
[eventComps setSecond: secs - nowComps.second];
eventDate = [cal dateByAddingComponents:eventComps toDate:now  options:0];

return eventDate;
}

Here, we take the newly created eventDate and use it to create our event in iCal:

        EKEventStore *eventStore = [[EKEventStore alloc] init];

        EKEvent *event  = [EKEvent eventWithEventStore:eventStore];
        event.title     = @"Move your car!";
        event.startDate = eventDate;
        event.endDate   = [[NSDate alloc] initWithTimeInterval:60.0f * 60.0f sinceDate:event.startDate]; //1 hr long
        [event addAlarm:[EKAlarm alarmWithRelativeOffset:60.0f * -30.0f]]; //30 min before
        //eventLoc was created using CLGeocoder and the method reverseGeocodeLocation:
        //The location is not necessary to create an event but if you'd like the code, ask and i'll post it.
        [event setLocation:eventLoc];
        [event setNotes:@"This event was set by me. ;P"];
        [event setCalendar:[eventStore defaultCalendarForNewEvents]];
        NSError *err;
        [eventStore saveEvent:event span:EKSpanThisEvent error:&err]; 
        NSLog(@"Event Set");

I hope this helps someone as much as it's helped me.

:END OF UPDATE:

I've read through the documentation of NSDate hoping to find an easy way to find "the next upcoming Mon 1:00PM".

For instance, lets say the bakery is open 1 day a week (Thurs) from 9am - 6pm... If it is now Thurs, 8am, I want to get an NSDate for 1hr from now. If today were Thurs @ 7pm, I'd want the NSDate for next Thurs at 9am.

I plan on making an event in iCal (tests have been successful) but the trouble is in calculating the event time.

Can you point me towards a good explanation of NSDate or help me figure out how to calculate the NSDate's I'm looking for?

I'm looking to fix this code:

    EKEventStore *eventStore = [[EKEventStore alloc] init];

    EKEvent *event  = [EKEvent eventWithEventStore:eventStore];
    event.title     = @"Bakery's Open!";

    event.startDate = [[NSDate alloc] init];
    event.endDate   = [[NSDate alloc] initWithTimeInterval:600 sinceDate:event.startDate];

    [event setCalendar:[eventStore defaultCalendarForNewEvents]];
    NSError *err;
    [eventStore saveEvent:event span:EKSpanThisEvent error:&err]; 

Solution

  • To find a date like this requires using NSDateComponents and NSCalendar. The main task, I think, is to figure out how many days in the future your target date is. To do this you need to get the weekday date component of the current date and calculate how many days it is to the weekday you're looking for. I think the following code should get you close:

    -(NSDate *)getNextDateOn:(NSString *)weekday atHour:(NSInteger)hour minute:(NSInteger)mins second:(NSInteger)secs {
    NSArray *array = [NSArray arrayWithObjects:@"Sunday",@"Monday",@"Tuesday",@"Wednesday",@"Thursday",@"Friday",@"Saturday",nil];
    NSInteger weekdayNumber = [array indexOfObject:[weekday capitalizedString]] + 1;
    NSDate *now = [NSDate date];
    NSCalendar *cal = [NSCalendar autoupdatingCurrentCalendar];
    NSDateComponents *nowComps = [cal components:NSWeekdayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit fromDate:now];
    NSInteger daysForward = (weekdayNumber - nowComps.weekday + 7) % 7;
    
    NSDateComponents *eventComps = [[NSDateComponents alloc] init];
    [eventComps setDay:daysForward];
    [eventComps setHour: hour - nowComps.hour];
    [eventComps setMinute: mins - nowComps.minute];
    [eventComps setSecond: secs - nowComps.second];
    NSDate *eventDate = [cal dateByAddingComponents:eventComps toDate:now  options:0];
    [eventComps release];
    return eventDate;
    

    }