Search code examples
objective-cnsdatenscalendarnsdatecomponents

From date cannot be nil in Objective-c


I'm trying to get the seconds between two dates, for this I'm using the NSDateComponents:

NSString *start = components2[0];// 2014-10-14 20:52:43
NSString *end = components[0];// 2014-10-14 20:54:40

NSLog(@"Start -> %@, End -> %@",start,end);

NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
NSDate *startDate = [f dateFromString:start];
NSDate *endDate = [f dateFromString:end];

NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components3 = [gregorianCalendar components:NSDayCalendarUnit
                                                    fromDate:startDate
                                                      toDate:endDate
                                                     options:0];



NSLog(@"Seconds -> %ld", (long)[components3 second]);

But I'm receiving the following error:

-[__NSCFCalendar components:fromDate:toDate:options:]: fromDate cannot be nil


Solution

  • If your date strings use 24-hour times, you must use HH as the hour format:

    [f setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    

    When an NSDateFormatter can't parse a date string, it returns nil.

    Once you get that straightened out, you'll find that [components3 second] has the strange value 9223372036854775807 (or 2147483647 on a 32-bit system), which is actually NSUndefinedDateComponent. You didn't ask for the number of seconds between the dates; you asked for the number of days. Use NSSecondCalendarUnit to ask for the number of seconds.