-3

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

Cœur
  • 37,241
  • 25
  • 195
  • 267
user3781174
  • 245
  • 5
  • 16
  • Well, what the message says -- `fromDate` is nil, and they don't allow that. If you look at `startDate` (and probably `endDate` too), it's nil, because you used the wrong date format. http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns – Hot Licks Oct 14 '14 at 21:00
  • If you're strictly looking for seconds between two dates, then do: `NSTimeInterval secondsElapsed = [endDate timeIntervalSinceDate:startDate]` But your question is really asking "why can't I get a date from the formatter" :) – Tim Reddy Oct 14 '14 at 21:05
  • Sorry Srs but the user Rob Mayoff do the right, the problem is using HH... – user3781174 Oct 14 '14 at 21:09

1 Answers1

2

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.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
  • Thanks, it works but I receive other problem, the slog returns me the value 2147483647 and I think this is not good.... – user3781174 Oct 14 '14 at 21:08